The following code is an example from MSDN:
private void Form1_Paint(object sender,
System.Windows.Forms.PaintEventArgs pe)
{
// Declares the Graphics object and sets it to the Graphics object
// supplied in the PaintEventArgs.
Graphics g = pe.Graphics;
// Insert code to paint the form here.
}
I have some questions:
Can we change the name of Form1_Paint method? I mean does it have to has "Paint" suffix? When does .net call this method? How does the framework know which method to call so it can draw images?
I don't understand how come we just define that Form1_Paint method can receive 2 arguments and then magically the framework just calls the method with a reference to object and a reference to an PaintEventArgs object(pe).
I am sorry for the dumb questions but I come from mainly functional programming and I am confused with using frameworks because it seems like they are calling on their own methods. Can someone please explain it like to a 6 year old?
As per the comment, Form1_Paint is an event handler for the Paint event.
The arguments aren't magic, they are required for this Event - i.e. if you want to bind to this event, your handler method implementation MUST match the event arguments required of it. A PaintEventHandler is defined as :
public delegate void PaintEventHandler(object sender, PaintEventArgs e);
By default, when you add a handler in the designer (e.g. by double clicking on a UI control or on the Events icon under the "lightning flash" tab), an event handler is automatically created with the default name:
{name of the control}_{name of event}
In your case, your form had the name Form1 when the handler method was created.
You can rename the handler method, but if you so so, you'll also need to change the corresponding event binding in the Form1.designer.cs (i.e. change this.Form1_Paint in the below):
this.Name = "Form1";
this.Text = "Form1";
this.Paint += new System.Windows.Forms.PaintEventHandler(this.Form1_Paint);
(+= indicates a subscription to the event - once subscribed, when the event is raised, all subscribing methods will be invoked)
Edit
Since you come from a FP background, you may be interested that there is no need for an explicitly named event handler, you can also subscribe a suitably typed lambda:
this.Paint += (sender, pe) =>
{
// Declares the Graphics object and sets it to the Graphics object
// supplied in the PaintEventArgs.
Graphics g = pe.Graphics;
// Insert code to paint the form here.
};
Where sender and pe have exactly the same types as before. The designer won't do this by default, so what you can do is programmatically add the above subscription to your Form1 constructor
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With