Capturing mouse down (form before control) event in vb.net (2010)
-
Thursday, September 23, 2010 10:47 AM
I'm working a program where I need to capture the mouse down even at the form level. I need this to happen regardless of where the mouse is clicked. The standard mouse event (see below) works fine if the mouse isn't over a control. However, when the mouse is over a control, the control gets the event before the form. I can generate an event to capture the mouse event for every control and the pass the event on, but that is ugly and requires way to much maintenance. Isn't there a way to tell vb that all mouse events go to the form?
Private
Sub Form1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseDown
...
All Replies
-
Thursday, September 23, 2010 10:56 AM
Create a single event handler, and register the control's mouse down to that one.
Thanks,
A.m.a.L
[MVP Visual C#]
Dot Net Goodies
Don't hate the hacker, hate the code -
Thursday, September 23, 2010 11:05 AM
Your question gave me an idea tested code for all, should work with all frameworks
Public Class Form1 Private Sub Form1_Load(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles MyBase.Load AddHandler Me.MouseDown, AddressOf MouseDownHandling MouseDownSetting(Me) End Sub Private Sub MouseDownSetting(ByVal parentCtr As Control) Dim ctr As Control For Each ctr In parentCtr.Controls AddHandler ctr.MouseDown, AddressOf MouseDownHandling MouseDownSetting(ctr) Next End Sub Private Sub MouseDownHandling(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) MessageBox.Show(DirectCast(sender, Control).Name) End Sub End Class
Success
Cor- Proposed As Answer by A.m.a.L HashimMVP Thursday, September 23, 2010 11:47 AM
- Marked As Answer by Martin_XieModerator Monday, September 27, 2010 4:20 PM
-
Thursday, September 23, 2010 11:44 AM
Cor,
That seems to have done it. Thank you!
As a follow on question, how would I forward the event to the proper control after I've handled the event at the form level?
Jim
-
Thursday, September 23, 2010 4:07 PM
Jim,
There is nothing to be done more, that code handles all controls which you have created at design time on your form.
Just try it by creating a new form project and drag some controls on your form, you will see that it works.
It is tested with one textbox, but that does not matter, even controls in other controls will have the same effect.
Success
Cor -
Thursday, September 23, 2010 6:46 PM
Cor,
Got it! I've gone through the code. I really appreciate the help. I had gone down a similar path but didn't see the recursive function. This is really good stuff!
Jim

