Microsoft KB Archive/75411

= How To Determine Whether TAB or Mouse Gave a VB Control the Focus =

Article ID: 75411

Article Last Modified on 2/11/2005

-

APPLIES TO


 * Microsoft Visual Basic 2.0 Standard Edition
 * Microsoft Visual Basic 3.0 Professional Edition
 * Microsoft Visual Basic 2.0 Professional Edition
 * Microsoft Visual Basic 3.0 Professional Edition
 * Microsoft Visual Basic 1.0 Standard Edition

-



This article was previously published under Q75411



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 &quot;User&quot; (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).

Keywords: kbhowto KB75411

-

[mailto:TECHNET@MICROSOFT.COM Send feedback to Microsoft]

© Microsoft Corporation. All rights reserved.