Link to home
Start Free TrialLog in
Avatar of vollmesg
vollmesg

asked on

Keypress for any control on form

I am using visual basic 2010 and I am trying to determine if there is any activity on a form (keypresses, mourseclicks, etc).  Is there any way to do this besides adding a keypress and mouseclick event on every control?
ASKER CERTIFIED SOLUTION
Avatar of slightwv (䄆 Netminder)
slightwv (䄆 Netminder)

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
For the KeyPress, you can set the KeyPreview property of the Form to True, and you will be able to grab all the key presses in the Form KeyPress event before they go to the individual controls.

For the other events, you can do the following.

Create the event procedure for one of the controls.

Remove the Handles clause at the end of the method declaration.

Add something like the following code at the end of the Form_Load event:
For Each ctl As Control In Me.Controls
    AddHandler ctl.<EventName>, AddressOf <NameOfTheEventProcedure>
Next

Open in new window

Here is one for the MouseClick:
For Each ctl As Control In Me.Controls
    AddHandler ctl.MouseClick, AddressOf TextBox1_MouseClick
Next

Open in new window

Inside of the event, if you need to reference the control that triggerend the event, you can do the following with the sender parameter:
Private Sub TextBox1_MouseClick(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles TextBox1.MouseClick
    Dim callingControl As Control
    callingControl = DirectCast(sender, Control)
    MessageBox.Show("This has been called by " & callingControl.Name)
End Sub

Open in new window