Click to See Complete Forum and Search --> : Know the form tab press at form level


parineeta_a
August 19th, 2001, 10:33 AM
I have set the Form KeyPreview-True, to trap the
key events at form level, but how do i trap
the tab key. It is not responding at all on
tab press.

Please suggest.

John G Duffy
August 19th, 2001, 02:46 PM
I can detect the tab key in the From_KeyDown Event.

private Sub Form_KeyDown(KeyCode as Integer, Shift as Integer)
MsgBox KeyCode
End Sub



produces a "9" in the msgbox

John G

Iouri
August 20th, 2001, 07:13 AM
Catching keys (tab, arrows) without subclassing is not easy.

Form_KeyDown (or Form_KeyUp) will not catch all keys always.

If form has no controls, it will work.
If you add one textbox, it will work.

If you add second textbox, it will work for arrow keys, but Tab key will be 'eaten'.

If you add few buttons, VB will allow you to use arrow keys for navigation between buttons. But then
... Form_KeyDown will not be able to catch these arrow keys.

Here is the solution - it uses one API. You will be able to catch Tab key and arrow keys. If Form_KeyDown
is not able to receive a key, keyCheckTab or keyCheck will do it.

' Form1 (KeyPreview = true); add two textxboxes and two buttons
option Explicit
private Declare Function GetKeyState Lib "user32" (byval nVirtKey as Long) as Integer

private Sub Form_KeyDown(KeyCode as Integer, Shift as Integer)
print KeyCode
End Sub

private Sub Command1_LostFocus()
' add this code to LostFocus event of your buttons
keyCheck
End Sub

private Sub Command2_LostFocus()
keyCheck
End Sub

private Sub Text1_LostFocus()
' add this code to LostFocus event of your textboxes
keyCheckTab
End Sub

private Sub Text2_LostFocus()
' add this code to LostFocus event of your textboxes
keyCheckTab
End Sub

private Sub keyCheck()
If GetKeyState(vbKeyTab) < 0 then
print "Tab pressed"
ElseIf GetKeyState(vbKeyLeft) < 0 then
print "Left pressed"
ElseIf GetKeyState(vbKeyRight) < 0 then
print "Right pressed"
ElseIf GetKeyState(vbKeyUp) < 0 then
print "Up pressed"
ElseIf GetKeyState(vbKeyDown) < 0 then
print "Down pressed"
End If
End Sub

private Sub keyCheckTab()
If GetKeyState(vbKeyTab) < 0 then
print "Tab pressed"
End If
End Sub


Iouri Boutchkine
iouri@hotsheet.com