Re: Detecting mouse click

Tech Tip: Click here to run a free scan for Windows Errors and optimize PC performance




"Ole Engvoll" <ole@xxxxxxxxxxx> wrote
Hi!
Is there some way to return the control name wherever a user click on
a form? Its not possible to use the form_click event since it is not
triggered if clicking on a control inside the form. I know this can be
done with a code on every control, but that is veeery time consuming.
I really hope there is another easier way.

Placing code in each click event is about the only way, but you can make
your job easier using a bit of code. What you end up doing is supplying
a class that will accept a control to watch and call into your form when
that control is clicked. A simple method is shown below, but only a few
of the different control types are handled. You would have to extend the
routines to include all the types you want to watch.

Add a class (Class1) module to a new project and put some controls on
the default form (Form1). Then paste in the code below and try it out....

HTH
LFS


' FORM1 code

Option Explicit
Private Hold As New Collection

Private Sub Form_Load()
Dim ctl As Object, trg As Class1

For Each ctl In Controls
Set trg = New Class1
If trg.Trigger(ctl, Me) Then
Hold.Add trg
End If
Next
List1.AddItem "Item 1"
List2.AddItem "Item 1"
End Sub

Public Sub ControlClick(Name As String)
MsgBox "Clicked on " & Name
End Sub


' CLASS1 code

Option Explicit

Private WithEvents cmd As CommandButton
Private WithEvents tbx As TextBox
Private WithEvents pic As PictureBox
Private WithEvents lst As ListBox
Private WithEvents lbl As Label
' ... for all required controls
Private ClickTarget As Form


Public Function Trigger(Source As Object, Target As Form) As Boolean
Set ClickTarget = Target
If TypeOf Source Is CommandButton Then
Set cmd = Source
Trigger = True
ElseIf TypeOf Source Is TextBox Then
Set tbx = Source
Trigger = True
ElseIf TypeOf Source Is Label Then
Set lbl = Source
Trigger = True
ElseIf TypeOf Source Is PictureBox Then
Set pic = Source
Trigger = True
ElseIf TypeOf Source Is ListBox Then
Set lst = Source
Trigger = True
' ... For all required controls
End If
End Function

' Capture click event for all required controls ...
Private Sub cmd_Click()
ClickTarget.ControlClick cmd.Name
End Sub

Private Sub lbl_Click()
ClickTarget.ControlClick lbl.Name
End Sub

Private Sub lst_Click()
ClickTarget.ControlClick lst.Name
End Sub

Private Sub pic_Click()
ClickTarget.ControlClick pic.Name
End Sub

Private Sub tbx_CLick()
ClickTarget.ControlClick tbx.Name
End Sub





.


Quantcast