简体   繁体   English

将焦点设置到另一个控件

[英]Set focus to another Control

我想在C#Windows应用程序(C#2005)中在textbox1中按ENTER键时将焦点从一个textbox1设置到另一个textbox2

处理textbox1KeyPressKeyDown事件,然后调用textbox2.Focus()

First, you will have to set the KeyPreview property of the Form set to true . 首先,您必须将Form的KeyPreview属性设置为true Then you will have to override the form's OnKeyDown method and make a case like: 然后,您将不得不重写表单的OnKeyDown方法,并进行如下操作:

if(e.KeyCode == Keys.Enter)
{
      Control ctlNext = this.GetNextControl(this.ActiveControl, true);
      ctlNext.Focus();
}
else
{
      base.OnKeyDown(e);
}

Mind you that this code will work for every control on the form, and move the focus to the next one. 请注意,此代码将适用于表单上的每个控件,并将焦点移至下一个控件。 If you just want this code to work for the textboxes you could add a check like: 如果您只想让此代码适用于文本框,则可以添加如下所示的复选框:

if(this.ActiveControl is TextBox)
{
...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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