问题
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.
回答1:
go to the properties of text box and assign correct order of tabindex
回答2:
Why do you need that complication at all? WinForms does it for you automatically. You just need to set the correct tab order.
回答3:
You should use tabOrder instead.
回答4:
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...
回答5:
You can try overriding the ProcessCmdKey method like this
回答6:
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.
回答7:
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:
Set the
TabStop = False
property
of all the textboxes. By default, this 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(); }
来源:https://stackoverflow.com/questions/2954911/how-to-detect-tab-key-pressing-in-c