2009-01-21

How To Trap TAB Key

Have you ever faced any situation wherein you wanted to trap the TAB key and do some stuff. Lets say for example, you want to trap the TAB key on a Textbox control and want to process some logic. TAB key cannot be trapped in the KeyrPress event. TAB key can be trapped with ProcessCmdKey and ProcessTabKey methods. But in this case I prefer ProcessCmdKey. In ProcessCmdKey method, we can cancel the processing of TAB key but that is not the case with ProcessTabKey method. It just traps the TAB key, it doesn't gives you any control over TAB key.

In one of my Interop project, I was using True DBGrid control of ComponentOne. In that project, the grid was throwing an exception in some scenarios when TAB key is pressed. The exception was thrown by the control itself, so I didn't had any control on it. That's why I chose ProcessCmdKey to trap the TAB key. I trapped the key and manually set the focus to the next control. This is how ProcessCmdKey came to my rescue. I am posting the code below that I used in my project.

''' 
''' Process the windows messages manually.
''' Trap the TAB key pressed on grid and suppress it.
''' Pressing the TAB key in FilterBar of C1 True DBGrid causes exception.
'''

'''
'''
'''
'''
Protected Overrides Function ProcessCmdKey( _
ByRef msg As Message, ByVal keyData As System.Windows.Forms.Keys _
) As Boolean

' Declare a variable of type Keys enumeration named keyPressed.
' Cast the msg's WParam as a KeyEnum value and assign it to the
' keyPressed variable.
Dim keyPressed As Keys = CType(msg.WParam.ToInt32(), Keys)
Dim ctrlType As String = "C1.Win.C1TrueDBGrid.GridEditor"

' Process keyPressed.
Select Case keyPressed
Case Keys.Tab
If Me.ActiveControl.ToString.StartsWith(ctrlType) Then
If grdSamples.EditActive = False Then
txtInstrument.Focus()
End If
' Cancel the TAB key message
Return True

' You can also trap the TAB key for button or TextBox
ElseIf Me.ActiveControl.Name = "btnClose" Then
grdSamples.Focus()
' Cancel the TAB key message
Return True
End If
Case Else
' Return the key message so it can be processed by this control.
Return MyBase.ProcessCmdKey(msg, keyData)
End Select
End Function

No comments: