Is it possible for a user to perform some action in WinForms (e.g. clicking a button) and have some arbitrary code executed on the UI thread before the event handler for that action is executed on the UI thread? (Edit: I don't want to do this myself. I want to know if it can actually happen. As in, do I need to worry about it?)
I'm a little fuzzy on how event handlers get called in .NET for GUI events, and I have run into a situation where that implementation detail is important.
**Edit***
I'm not concerned with how to connect an event handler or even how to raise the event programatically. I'm concerned with the under-the-hood details of how the event handler that I've already hooked up gets called as a result of the UI action. More specifically, I'm curious if the calling of the event handler (or the sequence of events that leads up to it) is simply added to the message loop for the form. It might be easier to show the UI thread "visually"...
Time --------->
Physical Click Detected .......(can other stuff hit the UI thread here)........... Click Event Handler Called
There are two options to accomplish this.
Most controls in Windows Forms provide a method that is used to raise the event. If you subclass the control, you can place your custom code in the method prior to raising the event.
For example, you could subclass Button, and override OnClick:
override void OnClick(EventArgs e)
{
// Your code here...
base.OnClick(e); // This will raise the Click event
}
The other option is to subscribe to the event first, and put your code in an event handler. Event handlers, by default, will call each delegate subscribed in order.
I'm concerned with the under-the-hood details of how the event handler that I've already hooked up gets called as a result of the UI action. More specifically, I'm curious if the calling of the event handler (or the sequence of events that leads up to it) is simply added to the message loop for the form.
When the user clicks a button, the mouse events are posted to the message loop for the application. The Button handles this message in a WndProc override (by handling a message defined as WM_REFLECT + WM_COMMAND).
If your question is "can other code run between the instant the user clicks and an event handler", then yes - code can be running when the user clicks, and that code will continue to run until the message pump can process the messages.
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