Intercept WinForms Events
You can examine the events WinForms raises before it sends them to subscribers.
by Juval Löwy
November 2003 Issue
Technology Toolbox: C#, VB6, Unmanaged C++
Q. Intercept WinForms Events
I need to do some precall processing and examine the events WinForms raises before it dispatches them to the subscribers. How do I do this?
A.
WinForms converts Windows messages to delegate-based events. Every control or form has a list of delegate-based events, each of which corresponds to a Windows message. You can place your event- or message-handling code at any point. One end of the spectrum is the raw message level (read the "Handle Windows Messages" topic in the March 2003 Q&A column, "Convert Integers to Byte Arrays"). At the other end, you can provide a method to handle the event; the visual designer does this by default. The in-between option is to place the code after the raw message processing, but before WinForms converts the message to the event. The Form class's WndProc method contains a switch statement that calls individual protected methods to handle the message. The message-handling method raises the corresponding delegate-based event. For example, consider your form's Load event. WinForms raises this event in response to the WM_SHOWWINDOW Windows message.
The Form class converts Windows messages to delegate-based events (see Listing 1). Listing 1 shows the Form class's implementation in pseudocode. The actual implementation details are somewhat different (Form uses an event list instead of individual event members, but the event accessors present a façade as if these were individual events), yet the essence of how Form converts Windows messages to delegate-based events is the same. The Form class's WndProc method calls the OnLoad method in response to the Windows message. The OnLoad method handles the message, then raises the delegate-based event associated with the message by invoking the Load event. Form includes similar methods—such as OnActivate, OnClick, and so on—for every event type. You must override the matching method if you want to intercept the message before it's converted to a delegate-based event:
public class MyForm : Form
{
protected override void
OnLoad(EventArgs e)
{
/* Do some event processing,
then: */
base.OnLoad(e);
}
}
Be sure to call the base-class implementation so the base class raises the delegate-based event.
Back to top
|