How to detect tab keystroke in C #?

I want to determine if the tab key is pressed in the text box and focus the next text box on the panel.

I tried the keyPressed and keyDown method. But when I run the program and debug, these methods do not call 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. Thanks.

+4
source share
7 answers

go to text box properties and assign the correct tab index order

+6
source

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

+10
source

Instead, use tabOrder.

+3
source

You want to leave the 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 expected. Obviously, you can do anything you like in the Leave() handler, including forcing focus in another place, but be careful not to confuse the user ...

+1
source

You can try to override the ProcessCmdKey method like this

+1
source

If the textBoxName has focus by pressing the TAB key, only the KeyDown event is fired. You just need to set the correct tab order.

0
source

If you are dealing with text fields inside a panel, setting the correct tab index should do the job perfectly. But, if you are dealing with a different text field from another panel, say:

panel1 has textbox1

panel2 has a text field2

panel3 has a text field3

Here is what you need to do:

  • Set TabStop = False property all text fields. By default, this parameter is set to True.

  • Set the correct TabIndex for each panel, e.g.

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

  • Then try this code

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

0
source

Source: https://habr.com/ru/post/1311581/


All Articles