Unless I make "static CPaintDC dc(this);" the line won't draw? But this is not good as it will eventually error, also the graphics wont' keep on the screen.
Not sure what I am doing wrong
Note: I have a Timer that calls to this every 100ms(x and y are incremented) thx
void CGraphicsDlg::OnPaint()
{
CString s;
CPaintDC dc(this);// device context for painting
if (IsIconic())
{
SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else if(x==0)
{
s.Format("%d", x);
edXa->SetWindowText(s);
dc.MoveTo(20,400);
}
else if (x>0){
s.Format("%d", x);
edXb->SetWindowText(s);
dc.LineTo(20 + x, 40); // doesn't draw unless I make "static CPaintDC dc(this);" <- which will error out
}
CDialog::OnPaint();
}
void CGraphicsDlg::OnTimer(UINT nIDEvent)
{
if(nIDEvent==1){
srand( (unsigned)time( NULL ) );
//y = rand() % 100;
y++;
x++;
OnPaint();
}
}
LineTo
draws a line from one point to another, using the selected pen. You need to use MoveTo
to define the start of the line, and you need to select a pen into the DC.
The larger problem is how you're trying to use the DC. It isn't meant to be permanent; you're supposed to acquire it, draw everything to it, then shut it down. When you try to make CPaintDC
static, Windows will eventually shut it down and every attempt to use it thereafter will return an error.
The proper way is to save any coordinates that you need for all of the drawing you need to do. Use a combination of MoveTo
and LineTo
to draw individual line segments, and every time you reenter OnPaint you need to start over.
dc.SelectObject
to select it. You have code to do a MoveTo
, but you need to do both at the same time. The MoveTo
will be lost the next time OnPaint is called - Mark Ransom 2012-04-03 21:30
Using the "pens" has helped... thank - jdl 2012-04-03 22:22
I am not answering your question, but have you noticed that CDialog::OnPaint() will be called even if IsIconic() returns TRUE ?
I think you will need to use an extra pair of {} to solve this ;-)