[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Use WndProc to read Windows messages in C#


This example shows how you can determine what windows messages a program is receiving. (In earlier versions of Visual Basic, you could intercept messages by using API functions to install a WndProc handler. That was called "subclassing" so the method described here is also sometimes called "subclassing," even though neither technique is truly subclassing in the object-oriented sense.)

Every form has a method called WndProc that processes Windows messages. This function handles messages telling the form to move, resize, redraw, close, display system menus, and all sorts of other things. Without it, the form can't do anything.

To see what messages the form is receiving, you can override WndProc as shown in the following code.

// Override WndProc to watch for messages. protected override void WndProc(ref Message m) { Console.WriteLine(m.ToString()); base.WndProc(ref m); }

This function receives a Message object as a parameter and uses its ToString method to display the message's name. You could make the program take other actions such as ignoring some messages.

The code then calls the base class's WndProc method to process the message normally. This is very important! If you don't process the message normally, the form will not be able to resize itself, draw its interior, and perform other important Windows functions.

Download the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.