Microsoft KB Archive/277916

= How To Use GetKeyState to Check If the TAB Key Was Pressed =

Article ID: 277916

Article Last Modified on 7/13/2004

-

APPLIES TO


 * Microsoft Visual Basic 6.0 Professional Edition
 * Microsoft Visual Basic 6.0 Enterprise Edition

-



This article was previously published under Q277916



SUMMARY
When you press the TAB key while the focus is on a control, the focus goes to the next control in the TAB order, and the KeyPress, KeyUp, and KeyDown events of the original control do not fire. As a result, you cannot use these events to trap the TAB key. However, you can use the GetKeyState function to check if the TAB key was pressed.



MORE INFORMATION
To check if the TAB key was pressed, follow these steps:  Start a Standard EXE project in Visual Basic. Form1 is created by default. Add a Textbox and a CommandButton to Form1. Set the CausesValidation property of the Textbox to True.  In the code module of Form1, add the following code: Option Explicit

Private Declare Function GetKeyState Lib &quot;user32&quot; (ByVal nVirtKey As Long) As Integer

Private Sub Text1_KeyDown(KeyCode As Integer, Shift As Integer) Debug.Print &quot;in keyDown&quot; End Sub

Private Sub Text1_KeyPress(KeyAscii As Integer) Debug.Print &quot;in keyPress&quot; End Sub

Private Sub Text1_KeyUp(KeyCode As Integer, Shift As Integer) Debug.Print &quot;in keyUp&quot; End Sub

Private Sub Text1_Validate(Cancel As Boolean) Dim retval As Integer

retval = GetKeyState(vbKeyTab) If retval < 0 Then Debug.Print &quot;Tab key was pressed in Text1&quot; End Sub  Press the F5 key to run the project. The focus is in the Textbox. Press the TAB key, and the focus shifts to the CommandButton. Check the Immediate window. Although the KeyPress, KeyUp, and KeyDown events do not fire, the Validate event indicates that the Tab key was pressed.</ol>

Additional query words: tab trap GetKeyState

Keywords: kbhowto kbapi kbcodesnippet KB277916

-

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

© Microsoft Corporation. All rights reserved.