I'd prefer doing this via
IMessageFilter
interface and
Application.AddMessageFilter
. Please refer to this sample implementation:
public class MessageFilter : IMessageFilter
{
long countMouse;
Form1 form;
public MessageFilter(Form1 form)
{
countMouse = 0;
this.form = form;
}
private const int WM_LBUTTONDOWN = 0x201;
public bool PreFilterMessage(ref Message m)
{
if (m.Msg == WM_LBUTTONDOWN)
{
countMouse++;
form.label1.Text = String.Format("Clicks: {0}", countMouse);
}
return false;
}
}
in the Program code where the Application is setup do this:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 form = new Form1();
Application.AddMessageFilter(new MessageFilter(form));
Application.Run(form);
}
}
Please take note that this is
only for demonstration purposes. I'd never make a Label public as it needs to be in this simple example, but it's enough for a simple demonstration. The filter will be called even when you click on however deeply nested controls. The message filter should also be unaware of the concrete form implementation. This was also done only for demonstration purposes.
Happy programming and cheers!
-MRB