I've noticed in C# I can override methods in the Form() parent class, like so:
protected override void OnPaint(PaintEventArgs e)
{
}
I don't understand how PaintEventArgs
is generated and how/when it is passed to this function. I've got to assume OnPaint()
is called every time the form needs repainting.
Furthermore, when I create button press events they look like this:
private void button1_Click(object sender, EventArgs e)
{
}
Once again, I don't understand how/why these parameters are passed when a button click is activated.
There is nothing special about it. The base class that defines the Paint
event contains code morally equivalent to this:
protected virtual void OnPaint(PaintEventArgs e)
{
var paintHandlers = this.Paint;
if (paintHandlers != null)
{
paintHandlers(this, e);
}
}
OnPaint
serves two functions:
Paint
event so external subscribers can be notified (that's how a hypothetical form1_Paint
will eventually get called).When the time comes to raise the Paint
event, some other code in the base class creates a PaintEventArgs
instance based on information at hand and calls OnPaint
:
// ...somewhere in the class...
OnPaint(new PaintEventArgs(...));
In the special case where the event argument is typed as EventArgs
there is no need to create a new instance, you can directly pass the EventArgs.Empty
static member to the OnSomething
method.
As to the when this happens: whenever a message is drawn from the application's message pump and processing it indicates that the event should be raised. You might also want to read Understanding events and event handlers in C#.
In the case of the button click event handler, the object sender, EventArgs e
syntax allows for multiple buttons to be wired up to a single event handler. This is possible, because the sender
is the object that initiated the event, thus you can differentiate if button1, button2 or button3 initiated the event.
And since the sender
is an object
, then you could conceivably have a single click handler that handled all page elements that were clickable and have a bunch of conditional logic in the handler to switch based on what type of control initiated the event; this is not recommended though.
The best place to start is to (re?)familiarize yourself with .Net "delegates":
For example, if you looked at the code for a C# form, you might see something like this:
private void btnGo_Click(object sender, EventArgs e)
{
// My code goes here...
Now if you looked at the corresponding, auto-generated, .Design code, you'd see something like this:
private void InitializeComponent()
{
this.btnGo.Click += new System.EventHandler(this.btnGo_Click);
....
The "+=" syntax assigns your custom event handler to the button. Any tutorial on "delegates" (including the link I cited above) will give you more details about how and why this works.
I hope that helps .. PSM
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