Axarydax
Axarydax

Reputation: 16603

How to intercept capture TAB key in WinForms application?

I'm trying to capture the Tab key in a Windows Forms application and do a custom action when it is pressed.

I have a Form with several listViews and buttons, I've set the Form's KeyPreview property to true and when I press any other key than tab, my KeyDown event handler does get called.

But that's not true with the Tab key - I don't receive WM_KEYDOWN message even in WndProc.

Do I need to set each control inside my form - its TabStop property - to false? There must be a more elegant way than that.

Thanks.

Upvotes: 13

Views: 19257

Answers (4)

Ram
Ram

Reputation: 1117

This is the C# code similar to the VB code given in the answer above...

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        if (keyData == Keys.Tab)
        {
            //your code
        }
        return base.ProcessCmdKey(ref msg, keyData);
    }

Hope this helps...

Upvotes: 35

user3044760
user3044760

Reputation: 1

Private Sub form1_KeyDown(.... ) Handles Me.KeyDown
    If e.KeyCode = Keys.Enter Then
        SendKeys.Send("{tab}")
    End If
End Sub

Upvotes: -1

Amsakanna
Amsakanna

Reputation: 12934

will this help you?

Protected Overrides Function ProcessCmdKey(ByRef msg As Message, ByVal keyData As Keys) As Boolean
  Dim keyPressed As Keys = CType(msg.WParam.ToInt32(), Keys)

  Select Case keyPressed
    Case Keys.Right msgbox("Right Arrow Key Caught")
    Case Keys.Left msgbox("LeftArrow Key Caught")
    Case Keys.Up msgbox("Up Arrow Key Caught")
    Case Keys.Down msgbox("Down Arrow Key Caught")
    Case Else Return MyBase.ProcessCmdKey(msg, keyData)
  End Select
End Function 

Upvotes: 9

Vicente
Vicente

Reputation: 81

You can use "PreviewKeyDown" Event

Upvotes: 8

Related Questions