5

i saw some similar questions on the site but none of them really helped me.

I have a function that draws a few lines on the form when a button is clicked that vary in shape depending on the values the user enters in some textboxes.

My problem is that when i minimize the form, the lines disappear and i understood that this can be resolved by using the OnPaint event, but i don't really understand how.

Can anyone give me a simple example of using a function to draw something at the push of a button using the OnPaint event?

Yuck
  • 49,664
  • 13
  • 105
  • 135
Stefan Manciu
  • 490
  • 1
  • 6
  • 19

2 Answers2

6

Here you go, simpe MSDN tutorial on User-Drawn Controls

You must inherit Button class and override OnPaint method.

Code example:

protected override void OnPaint(PaintEventArgs pe)
{
   // Call the OnPaint method of the base class.
   base.OnPaint(pe);

   // Declare and instantiate a new pen.
   System.Drawing.Pen myPen = new System.Drawing.Pen(Color.Aqua);

   // Draw an aqua rectangle in the rectangle represented by the control.
   pe.Graphics.DrawRectangle(myPen, new Rectangle(this.Location, 
      this.Size));
}

EDIT:

Add property to your class and like public Color MyFancyTextColor {get;set;} and use it in your OnPaint method. Alsow it will apear in control property editor of visual studio form designer.

Pavel Krymets
  • 6,253
  • 1
  • 22
  • 35
  • But if i do this and i put my drawing function in the OnPaint method, how do i pass the values for the function's parameters from the form? – Stefan Manciu Apr 10 '12 at 13:02
  • Ok, i did it, but i still have a problem : everytime the mouse cursor hovers over the buttons, the OnPaint method is called. How can i make it so that it ignores buttons? – Stefan Manciu Apr 10 '12 at 20:40
3

You can write all the code responsible for (re)drawing the scene into method called when Paint event occurs.

So, you can register you method to be called when Paint occurs like this:

this.Paint += new PaintEventHandler(YourMethod);

Then YourMethod will be called whenever the form needs to be redrawn.

Also remember that you method must have the same arguments as delegate, in this case:

void YourMethod(object sender, PaintEventArgs pea)
{
   // Draw nice Sun and detailed grass
   pea.Graphics.DrawLine(/* here you go */);
}

EDIT

Or, as mentioned in another answer, you can override OnPaint method. Then you don't have to take care about adding event handler with your own method.

Miroslav Mares
  • 2,292
  • 3
  • 22
  • 27
  • So if i put my drawing function in YourMethod, everytime the form needs to be redrawn, it will call the function? If so, how do i get the parameters for my function? – Stefan Manciu Apr 10 '12 at 13:05
  • Yes, it will. You don't need to take extra care about the arguments, because they are passed to YourMethod by runtime. – Miroslav Mares Apr 10 '12 at 14:24