0

In my code I am drawing a rectangle as a "frame" of a Panel. I am getting the required color from XML file as a string (like "red", "blue" etc.). While creating the panel, I am painting it using this code:

                    Strip.Paint += (sender, e) =>
                {
                    //MessageBox.Show(clr.ToString());
                    Pen p = new Pen(Color.FromName(color), 2); // color is the string with name of the color
                    Rectangle r = new Rectangle(1, 1, 286, 36);
                    e.Graphics.DrawRectangle(p, r);
                    p.Dispose();
                    e.Dispose();
                };

In the method that is supposed to refresh the rectangle, I add this line

Strip.Refresh();

This works fine. But, using Timer every 30 seconds I check if the color has changed, and
if it did, redraw the rectangle with requested color. The first rectangle draws correctly. But when the Timer reaches 30, it just... Well I am not sure even how to describe it, here is the picture what it does after "refreshing": Printscreen of the application before and after refresh, excluding the text "normal state" and "after refresh" no edit, it really does this

Marek Buchtela
  • 973
  • 3
  • 19
  • 42
  • Note: it shouldnt even be red after the refresh, I have no idea why it turns everything red.. – Marek Buchtela Dec 30 '12 at 14:17
  • Okay, I found out why it crossed _all_ of them, I had a mistake in code deciding if the color has changed or not. So it is okay with those, which arent supposed to redraw. But when the color changes, it still does this. – Marek Buchtela Dec 30 '12 at 14:36

1 Answers1

2

The "Red Cross" is what happens when an exception is thrown inside a OnPaint method. It means that you have a bug in your code inside the Paint lambda.

Once an exception is thrown, an internal flag is set and the control will no longer attempt to repaint itself. This is reset only when the application is run again, or when this trick is performed.

I suspect know the problem in your case is that you are not supposed to Dispose() the PaintEventArgs object in a Paint event.

In general, you should not have to dispose of objects you did not create yourself.

Rotem
  • 21,452
  • 6
  • 62
  • 109