How to intercept the TAB key press to prevent standard focus change in C#

后端 未结 5 766
伪装坚强ぢ
伪装坚强ぢ 2021-01-19 04:36

Normally when pressing the TAB key you change the focus to the next control in the given tab order. I would like to prevent that and have the TAB key do something else. In m

相关标签:
5条回答
  • 2021-01-19 05:23

    Based on JRS's suggestion of using the PreviewKeyDown event, this sends the key press through to the control:

    private void textBox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
    {
        if (e.KeyCode == Keys.Tab)
            e.IsInputKey = true;
    }
    

    Then you can handle the control's KeyDown event if you want to customise the behaviour:

    private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Tab)
        {
            MessageBox.Show("The tab key was pressed while holding these modifier keys: "
                    + e.Modifiers.ToString());
        }
    }
    

    TextBoxBase alternative

    If the control is derived from TextBoxBase (i.e. TextBox or RichTextBox), with the Multiline property set to true, then you can simply set the AcceptsTab property to true.

    TextBoxBase.AcceptsTab Property

    Gets or sets a value indicating whether pressing the TAB key in a multiline text box control types a TAB character in the control instead of moving the focus to the next control in the tab order.

    0 讨论(0)
  • 2021-01-19 05:23

    Since I am building a UserControl, I ended up using the PreviewKeyDown event on the control. This avoids having to handle key press events on the host form.

    http://msdn.microsoft.com/en-us/library/system.windows.forms.control.previewkeydown.aspx

    0 讨论(0)
  • 2021-01-19 05:30

    Override ProcessDialogKey or ProcessTabKey on your Form and do the logic you want depending on which control is focused.

    0 讨论(0)
  • 2021-01-19 05:32

    Override the control's LostFocus event see link below for examples:

    http://msdn.microsoft.com/en-us/library/system.windows.forms.control.lostfocus.aspx

    0 讨论(0)
  • 2021-01-19 05:33

    You can try this code on your KeyDown event:

    if (e.KeyCode == Keys.Tab) {
      //your logic
      e.SuppressKeyPress = true;
    }
    

    If the button clicked is Tab, then do any custom logic you want, then call SuppressKeyPress to stop the KeyPress event from firing and invoking the normal Tab logic for you.

    0 讨论(0)
提交回复
热议问题