Hooking the Windows Message Loop in a WinForms Application

Provided by Dave Juth, Senior Systems Architect

The days of Windows API programming are just a memory for most, but .NET WinForms applications still allow you to hook Windows messages and respond to operating system events like the good old days.

The WndProc method of a form provides access to the Windows message loop for your application. You can monitor these messages in Visual Studio’s output window with the following code in a form:


protected override void WndProc(ref Message m)
{
  base.WndProc(ref m);

  Trace.WriteLine(m.Msg.ToString() + “: “ + m.ToString());
}


If you want respond to a particular message, such as a Windows shutdown event, the following code example illustrates how to do this:


protected override void WndProc(ref Message m)
{
  base.WndProc(ref m);

  if (m.Msg == 0×11)   // WM_QUERYENDSESSION
  {
    // TODO: Do something, then close the form.
    this.Close();
  };
}

There are many events exposed through the WinForms object model itself, but not all events are. Knowing how to hook into the operating system’s messaging is a powerful capability and, thanks to .NET, easily done.


Additional Resources

 

 

Thank you! Thank you! I just finished reading this document, which was part of a link in the recent Buzz newsletter. I have printed it for others to read, especially those skeptical on the powers of Access and its capabilities.

Darren D.


View all FMS products for Microsoft Access All Our Microsoft Access Products

 

 

Free Product Catalog from FMS