简体   繁体   中英

How to detect tab key pressing in C#?

I want to detect when tab key is pressed in a textBox and focus the next textbox in the panel.

I have tried out keyPressed method and keyDown method. But when I run the program and debug those methods are not calling when the tab key is pressed. Here is my code.

private void textBoxName_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Tab)
    {
        textBoxUsername.Focus();
    }
}

private void textBoxName_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar==(char)Keys.Tab)
    {
        textBoxUsername.Focus();
    }
}

Please correct me.Thank you.

Why do you need that complication at all? WinForms does it for you automatically. You just need to set the correct tab order.

转到文本框的属性并指定tabindex的正确顺序

您应该使用tabOrder。

You want the "leave" event. I just threw this into the default C# WinForms application:

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        /* 
              ... misc housekeeping ... 
        */

        private void OnLeave(object sender, EventArgs e)
        {
            lblMsg.Text = "left field 1";
        }

        private void OnLeave2(object sender, EventArgs e)
        {
            lblMsg.Text = "left field 2";
        }
    }
}

It works as you would expect. Obviously you can do anything you want in the Leave() handler, including forcing the focus elsewhere, but be careful not to confuse the user...

您可以尝试像这样重写ProcessCmdKey方法

If textBoxName has a focus while pressing the TAB Key , then only the "KeyDown" event triggers. You just need to set the correct tab order.

If you are dealing with the text boxes inside a Panel, setting the correct tab index should do the job perfectly. But, if you are dealing with other text box from other Panel say:

panel1 has textbox1

panel2 has textbox2

panel3 has textbox3

Here's what you need to do:

  1. Set the TabStop = False property of all the textboxes. By default, this is set to True.

  2. Set the correct TabIndex for each panel, eg

    panel1 TabIndex = 0; panel2 TabIndex = 1; panel3 TabIndex = 2;

  3. Then try this code

    private void textBox1_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode.Equals(Keys.Tab)) this.textBox3.Focus(); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM