How to capture tab key presses

  • Thread starter Thread starter Don
  • Start date Start date
D

Don

It took me a while to find this code, so I decided to post it here for
others who might also be looking for a way to trap tab key presses. You can
extend a control and place this code in it to raise a custom TabKeyDown
event. Here is an example of how you might extend a TextBox control to
provide this event:


Public Class TextBoxEx
Inherits TextBox

Const WM_KEYDOWN As Integer = &H100
Const WM_SYSKEYDOWN As Integer = &H104

Public Event TabKeyDown(ByVal CtrlPressed As Boolean, _
ByVal ShiftPressed As Boolean)

Protected Overrides Function ProcessCmdKey(ByRef msg As Message, _
ByVal keyData As Keys) As Boolean

' If a key or system key is pressed...
If ((msg.Msg = WM_KEYDOWN) Or (msg.Msg = WM_SYSKEYDOWN)) Then

' If the tab key is pressed...
If keyData = Keys.Tab Then

' The user pressed the tab key (without holding ctrl,
' shift, or alt)
RaiseEvent TabKeyDown((keyData And Keys.Control) = _
Keys.Control, (keyData And Keys.Shift) = Keys.Shift)

' If the tab key was pressed along with one or more
' other system keys...
ElseIf (keyData And Keys.Tab) = Keys.Tab Then

' The user held ctrl shift or alt and pressed the tab key
' Note: I don't bother to trap for the Alt key because
' Alt-Tab switches focus to another app and yours
' will not receive the message anyway.
RaiseEvent TabKeyDown((keyData And Keys.Control) = _
Keys.Control, (keyData And Keys.Shift) = Keys.Shift)

End If

End If

' Let base class handle the key press
Return MyBase.ProcessCmdKey(msg, keyData)

End Function

End Class


- Don
 
Don,

Is this not easier?

\\\
Private Sub TextBox1_KeyUp(ByVal sender As Object, _
ByVal e As System.Windows.Forms.KeyEventArgs) _
Handles TextBox1.KeyUp
If e.KeyData = Keys.Tab Then
MessageBox.Show("Hello Don")
End If
End Sub
///
 
I wish it were that easy, but pressing the tab key does not fire the
KeyUp/KeyDown/KeyPress events.

- Don
 
Back
Top