开发者

How to detect tab key pressing in C#?

开发者 https://www.devze.com 2023-01-01 16:14 出处:网络
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 method

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.Ke开发者_C百科yChar==(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.


go to the properties of text box and assign correct order of tabindex


You should use tabOrder instead.


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


You can try overriding the ProcessCmdKey method like this


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, e.g.

    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(); }

0

精彩评论

暂无评论...
验证码 换一张
取 消