13

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.

Jeff
  • 739
  • 12
  • 31
Axarydax
  • 16,353
  • 21
  • 92
  • 151

4 Answers4

35

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...

Ram
  • 1,097
  • 2
  • 12
  • 24
  • Certainly helped me. An upvote for providing the code for the language that the question was tagged under. – Logarr Feb 19 '13 at 16:18
  • This example continues propagation. You need to return 'true' from ProcessCmdKey to stop other handling of the key press, which is often the intended behavior (only one thing handles it). – DAG Jul 01 '18 at 14:37
  • @Ram, is there anyway to know on which control tabkey was pressed? – Zakir_SZH Jan 26 '19 at 15:05
9

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 
LarsTech
  • 80,625
  • 14
  • 153
  • 225
Amsakanna
  • 12,254
  • 8
  • 46
  • 58
  • 1
    yes! thanks. So for completion's sake, I had to override Form's ProcessCmdKey event and check if (keyData & Keys.Tab) == Keys.Tab. – Axarydax Mar 17 '10 at 12:01
  • 1
    Whilst this may theoretically answer the question, [it would be preferable](http://meta.stackexchange.com/q/8259) to include the essential parts of the answer here, and provide the link for reference. – Cody Gray - on strike May 22 '12 at 11:29
7

You can use "PreviewKeyDown" Event

Vicente
  • 71
  • 1
  • 1
-1
Private Sub form1_KeyDown(.... ) Handles Me.KeyDown
    If e.KeyCode = Keys.Enter Then
        SendKeys.Send("{tab}")
    End If
End Sub
  • that really doesn't have anything to do with the question - you intercept Enter key and send Tab afterwards... – Axarydax Nov 28 '13 at 19:40