Question Identify mouse click anywhere on the form + identify the control at that position

cosmins

New member
Joined
Oct 16, 2009
Messages
2
Programming Experience
3-5
Hi, I have the following problem:

When I click (shift + right mouse click) on a control (label, textbox, checkbox, etc) on a windows form I want to catch that event and identify the control the mouse was over. I can’t use MouseClick event for that control because I want to create a generic function for all forms/controls in the app.

Schematic the problem can be like this:
If mouseclick then
Find topmost control at that position
If controltype= label then Control.text=”Changed”
Elseif controltype=textbox then control.enabled=false


Can anybody help me with this?

Thanks.
 
I can’t use MouseClick event for that control because I want to create a generic function for all forms/controls in the app.
Yes you can. Just create a single MouseClick event handler and put every control in the Handles clause. When the event handler is invoked the 'sender' parameter contains a reference to the control that raised the event.

If you want to avoid a long Handles clause and also allow for adding new controls without having to change that code, leave off the Handles clause altogether and use AddHandler in the Load event handler:
VB.NET:
Private Sub Form1_Load(ByVal sender As Object, _
                       ByVal e As EventArgs) Handles MyBase.Load
    Dim ctl As Control = Me.GetNextControl(Me, True)

    Do
        AddHandler ctl.MouseClick, AddressOf HandleMouseClick
        ctl = Me.GetNextControl(ctl, True)
    Loop Until ctl Is Nothing
End Sub
 
Hi jmcilhinney, thanks for your help.

Your second suggestion sounds good (since you do not want to write a huge handle clause for hundreds of forms in an app); adding one line of code in each form_load sounds manageable.

Now all I have to do is figure out how to check if there is a mouse_click for each control and disable it before I add my generic HandleMouseClick.
Any ideas? :)
 
Now all I have to do is figure out how to check if there is a mouse_click for each control and disable it before I add my generic HandleMouseClick.
Any ideas? :)
There's nothing you can do about that. If there's a method with a Handles clause then that can't be removed using code. Only event handlers attached using AddHandler can be removed using RemoveHandler.

Because a Handles clause refers to a specific member variable, your only option would be to assign the control to a new variable and null the original one. That's not exactly practical though.
 
Back
Top