我在WinForm上有几个TextBox.当按下Enter键时,我希望焦点移动到下一个控件?每当文本框获得控制权时,它也会选择文本,以便任何编辑都将替换当前文本.
做这个的最好方式是什么?
ng5*_*000 30
选项卡输入:创建一个继承文本框的用户控件,覆盖该KeyPress方法.如果用户按下回车,您可以拨打SendKeys.Send("{TAB}")或System.Windows.Forms.Control.SelectNextControl().请注意,您可以使用该KeyPress事件实现相同的目标.
聚焦整个文本:再次,通过覆盖或事件,定位GotFocus事件然后调用TextBox.Select方法.
jim*_*415 23
C#中使用SelectNextControl的几个代码示例.
当按下ENTER时,第一个移动到下一个控件.
private void Control_KeyUp( object sender, KeyEventArgs e )
{
if( (e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Return) )
{
this.SelectNextControl( (Control)sender, true, true, true, true );
}
}
Run Code Online (Sandbox Code Playgroud)
第二个使用向上和向下箭头在控件中移动.
private void Control_KeyUp( object sender, KeyEventArgs e )
{
if( e.KeyCode == Keys.Up )
{
this.SelectNextControl( (Control)sender, false, true, true, true );
}
else if( e.KeyCode == Keys.Down )
{
this.SelectNextControl( (Control)sender, true, true, true, true );
}
}
Run Code Online (Sandbox Code Playgroud)
请参阅MSDN SelectNextControl方法
Pat*_*ald 11
在KeyPress事件中,如果用户按Enter键,则调用
SendKeys.Send("{TAB}")
Run Code Online (Sandbox Code Playgroud)
实现在接收焦点上自动选择文本的最好方法是在项目中使用以下覆盖创建TextBox的子类:
Protected Overrides Sub OnGotFocus(ByVal e As System.EventArgs)
SelectionStart = 0
SelectionLength = Text.Length
MyBase.OnGotFocus(e)
End Sub
Run Code Online (Sandbox Code Playgroud)
然后使用此自定义TextBox代替所有表单上的WinForms标准TextBox.