We help IT Professionals succeed at work.

How can i get the information how a control got focus

GuidoBartels
GuidoBartels asked
on
How can i get the information how a control got focus (mouse or key)?
Comment
Watch Question

Commented:
This can be kind of tricky, but here's a suggestion.

1) Put a break-point or a "stop" in the GotFocus event
2) Run the app and do whatever it is that's causing the control to get focus (code execution should stop b/c of #1)
3) Look at the call stack to see what code was executed just before the GotFocus event.  If you don't have a toolbar item for "Call Stack", it's also in the View menu.
TimCotteeHead of Software Services
CERTIFIED EXPERT

Commented:
You could use the MouseDown event to test whether the mouse was used. However if you use a variable to store this, reset it in the lostfocus event as it will not be set by any key used to set focus to it:

Dim Method As String

Private Sub Form_Load()
  Method = "Load"
End Sub

Private Sub MyControl_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)
  If Button = 1 Then Method = "Mouse"
End Sub

Private Sub MyControl_GotFocus()
  Msgbox "Got Focus By " & Method
End Sub

Private Sub MyControl_LostFocus()
  Method = "Key / Other"
End Sub
PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!

No comment has been added lately, so it's time to clean up this TA.
I will leave a recommendation in Community Support that this question is:
- PAQ/Refund.  Not fully answered IMO.  To do this generically would require subclassing the message stream and use of the screen.activecontrol, setting form.Keypreview = true and a variety of other API techniques.  However, I can go with TimCottee's answer as it does address it with a single control, but would not do so without feedback from either TimCottee or GuidoBartels.

Please leave any comments here within the
next seven days.
Commented:
Finalized as proposed

modulo

Community Support Moderator
Experts Exchange

Explore More ContentExplore courses, solutions, and other research materials related to this topic.