How to catch clicks on contained controls in the form.

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I would like to capture, in my form, any mouse clicks on controls contained
in the form.

I know I can do this using a mouse hook, but that has a few problems with
catching clicks on dialogs the form owns that I have not been able to work
out.

I want to catch the click, so I can lock the data source, and then let the
click go on its merry old way.

Any simple solutions that I am overlooking?

Thanks,
/ken
 
KenDev,

Ii is not as easy as it sounds. Mouse click go through the message loop
though, so you can register a message filter and catch the mouse events
there. The message filter will be called for the messages of all controls in
the applications, thus you need to filter out only thouse that are mouse
messages and are sents to the control's hosted by your form.

Something like this:

public partial class Form1 : Form, IMessageFilter
{




public Form1()
{
InitializeComponent();
Application.AddMessageFilter(this);

}



static int count = 0;



#region IMessageFilter Members
private const int WM_LBUTTONDOWN = 0x0201;
bool IMessageFilter.PreFilterMessage(ref Message m)
{
if (m.Msg == WM_LBUTTONDOWN)
{
Control target = Control.FromHandle(m.HWnd);
if (target != null && target.FindForm() == this)
{
Console.WriteLine("LMouseDown", count++);
return true;
}
}

return false;

}

#endregion
}

Even this solution is not perfect. For example some of the controls are
composit e.g. combobox has a list and edtitbox. Id the user click on the
edit box this won't catch the click becasue Control.FromHandle returns
*null* - there is no windows form control created for this HWND.
 
Back
Top