Windows Forms应用中如何通过按键切换TextBox及按钮的选中焦点
解决方案
在WinForms中,要实现控件间的焦点切换,直接调用目标控件的Focus()方法就可以,这就是你想要的类似this.SelectedItem = TxtBoxName的实现方式。以下是修改后的完整代码:
private void TxtBoxName_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { if(TextIsEmpty(TxtBoxDebt.Text)) { // 切换到TxtBoxDebt TxtBoxDebt.Focus(); } else { AssignNewPerson(); } } if (e.KeyCode == Keys.Down) { // 切换到TxtBoxDebt TxtBoxDebt.Focus(); } } private void TxtBoxDebt_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { AssignNewPerson(); } else if (e.KeyCode == Keys.Up) { // 切换到TxtBoxName TxtBoxName.Focus(); } else if(e.KeyCode == Keys.Down) { // 切换到TxtBoxNote TxtBoxNote.Focus(); } } private void TxtBoxNote_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { AssignNewPerson(); } else if (e.KeyCode == Keys.Up) { // 切换到TxtBoxDebt TxtBoxDebt.Focus(); } else if (e.KeyCode == Keys.Down) { // 切换到BtnAssign BtnAssign.Focus(); } }
额外优化建议
如果不想为每个控件单独写KeyDown事件,可以统一绑定一个公共事件处理方法,通过判断当前焦点控件来决定下一个焦点目标,减少重复代码。比如:
private void Common_KeyDown(object sender, KeyEventArgs e) { Control currentControl = sender as Control; if (currentControl == null) return; switch (e.KeyCode) { case Keys.Enter: AssignNewPerson(); break; case Keys.Up: if (currentControl == TxtBoxDebt) TxtBoxName.Focus(); else if (currentControl == TxtBoxNote) TxtBoxDebt.Focus(); break; case Keys.Down: if (currentControl == TxtBoxName) TxtBoxDebt.Focus(); else if (currentControl == TxtBoxDebt) TxtBoxNote.Focus(); else if (currentControl == TxtBoxNote) BtnAssign.Focus(); break; } }
之后只需要把所有TextBox和按钮的KeyDown事件绑定到这个Common_KeyDown方法即可。
内容的提问来源于stack exchange,提问作者semih yılmaz
相关产品推荐
相关产品推荐

