HOWTO: Determine Whether TAB or Mouse Gave a VB Control the Focus

ID: Q75411


The information in this article applies to:


SUMMARY

You can determine whether a Microsoft Visual Basic for Windows control received the focus from a mouse click or a TAB keystroke by calling the Microsoft Windows API function GetKeyState in the control's GotFocus event procedure. By using GetKeyState to check if the TAB key is down, you can determine if the user pressed the TAB key to get to the control. If the TAB key was not used and the control does not have an access key, the user must have used the mouse to click the control to set the focus.


MORE INFORMATION

The GetKeyState Windows API function takes an integer parameter containing the virtual key code for the desired key states. GetKeyState returns an integer. If the return value is negative, the key has been pressed.

The following is a code example. To use this example, start with a new project in Visual Basic for Windows. Add a text box and a command button to Form1. Enter the following code in the project's GLOBAL.BAS module:


   ' Global Module.
   Declare Function GetKeyState% Lib "User" (ByVal nVirtKey%)
   Global Const VK_TAB = 9 
Add the following code to the GotFocus event procedure for the Text1 text box control:

   Sub Text1_GotFocus()
      If GetKeyState(VK_TAB) < 0 Then
        Text1.SelStart = 0
        Text1.SelLength = Len(Text1.Text)
      Else
        Text1.SelLength = 0
      End If
   End Sub 
Run the program. If you use the TAB key to move the focus from the command button to the text box, you should see the text in the text box selected. If you change the focus to the text box by clicking it with the mouse, the text will not be selected.

An access key is assigned by using an ampersand (&) in the control's caption property. If the control has an access key, you may also want to check the state of the virtual ALT key by using GetKeyState to see if the user used the access key to change the focus. The virtual key code for ALT, actually known as VK_MENU, is 12H (&H12).

Additional query words:


Keywords          : kbVBp300 kbDSupport kbvbp200 
Version           : WINDOWS:1.0,2.0,3.0
Platform          : WINDOWS 
Issue type        : kbhowto 

Last Reviewed: July 13, 1999