2

I have a windows form which contains a user control. This user control has the following code:

protected override void OnPaint(PaintEventArgs pe)
{
  base.OnPaint(pe);
  pe.Graphics.DrawRectangle(
       new Pen(Color.Red, 5 + laenge), 
       new Rectangle(
             new Point(50 + leerzeichen, hoehe), 
             new Size(laenge + 20, 20)));
}

and some more code, which is probably not important now. So when I start the programm it draws the red rectangle. All the variables (laenge, leerzeichen, hoehe) are set to 0 at the beginning of the program. Now, when I press a button the variables are changing, but OnPaint does not draw the new rectangle? What could be the problem? Do I have to call OnPaint in some way?

Matten
  • 17,365
  • 2
  • 42
  • 64
Tim Kathete Stadler
  • 1,067
  • 4
  • 26
  • 52
  • 2
    is it possible that you are drawing multiple rectangles on the same coordinates? – daryal Jan 11 '13 at 08:44
  • 1
    Try to invalidate your control by calling the `Invalidate()` method. This will fire the paint routine. – Steve B Jan 11 '13 at 08:46
  • 1
    Be aware that the Pens you create in your OnPaint method are leaking! You need to dispose of them when you are finished. – Chris Dunaway Jan 11 '13 at 16:54

2 Answers2

5

You need to call Invalidate(), after changing variables (it calls OnPaint internaly)

Kamil Lach
  • 4,519
  • 2
  • 19
  • 20
0

You do not call OnPaint directly.

Rather, as inherited from Win32 (InvalidateRect()), the control's region needs to be invalidated (e.g. by calling Invalidate()) to cause Windows to call the control's OnPaint method during refresh. (see this question)

Be aware that the OS can process paint/refresh requests only when the application waits for the Windows message queue (i.e. it is done processing user requests, or calls Application.DoEvents()).

Community
  • 1
  • 1
devio
  • 36,858
  • 7
  • 80
  • 143