0

I have a picture control box (a CStatic) in a dialog. When the user presses a button in the dialog I need the onPaint() to draw an image in it. The problem is, The image is drawn at the loading of the dialog. How do I prevent this and call it only at button press.

My onPaint code;

void CStaticGraph::OnPaint()
{
    POINT xy[1000];
    CPaintDC dc(this); // device context for painting

    CRect Recto;
    char LocDim[80];

    GetWindowRect(&Recto);

    CPoint pBottom,pTop,pLeft;
    CPoint p[50];


    pBottom.SetPoint(0,0);
    pTop.SetPoint(0,Recto.Height());
    pLeft.SetPoint(Recto.Width(),Recto.Height());

    dc.MoveTo(pBottom);
    dc.LineTo(pTop);
    dc.LineTo(pLeft);

    int y[] ={80,120,180,200};
    int x=0;
    for(int i=0; i<sizeof(y);i++){
        p[i].SetPoint(Recto.Height()-x,y[i]);
        if(i>0){
                dc.MoveTo(p[i-1]);
                dc.LineTo(p[i]);


        }
        x+=50;
    }
}

As you can see I'm plotting a graph, I also need to pass data (the y[] values) at button press. I haven't done that yet.
Thanks.

Madz
  • 1,273
  • 2
  • 18
  • 35
  • My advice would be to create an ActiveX control (with either MFC or ATL) then embed that control in your dialog. Respond to the button by sending it the data, at which point it draws the graph. – Jerry Coffin Oct 02 '13 at 06:30
  • `sizeof()` gives you the total number of bytes in the array, not the number of elements. With VisualStudio, you should be able to use the `_countof()` macro to get the number of elelements. – Jim Rhodes Oct 02 '13 at 11:43

2 Answers2

1

Add a variable, such as a BOOL, to your CStaticGraph class to act as a flag to tell OnPaint() what to do. Initialize the variable in the constructor and change it when the button is clicked. For example:

In the header file for CStaticGraph add:

BOOL    m_fButtonPressed;

In the CStaticGraph constructor add:

m_fButtonPressed = FALSE;

In your button click handler do something like:

void CStaticGraph::OnButtonClick()
{
  m_fButtonPressed = TRUE;
  Invalidate();
}

Then in your OnPaint only draw the graph when flag is set:

void CStaticGraph::OnPaint()
(
  CPaintDC dc(this);

  if ( m_fButtonPressed )
  {
    // Clear the window
    return;
  }

  // Draw the graph
  . . .
}
Jim Rhodes
  • 5,021
  • 4
  • 25
  • 38
1

In addition to the Invalidate() in the other answer, you need to also change

for(int i=0; i<sizeof(y);i++)

to

for(int i=0; i<sizeof(y)/sizeof(int);i++)
Edward Clements
  • 5,040
  • 2
  • 21
  • 27
  • Why? I thought sizeof(y) returns the size of the array? – Madz Oct 02 '13 at 09:11
  • Accordingto [MSDN doc.](http://msdn.microsoft.com/en-us/library/4s7x1k91.aspx), `When the sizeof operator is applied to an array, it yields the total number of bytes in that array...` -- you can check the value in the debugger... – Edward Clements Oct 02 '13 at 14:26