在Enter事件中设置焦点的替代方法 [英] Alternative to set focus from within the Enter event
问题描述
我有一个文本框,并且在某些情况下,在Enter事件中,我需要将焦点设置为不同的文本框。
我试过这样的代码:
private void TextBox1_Enter(object sender,EventArgs e)
{
if(_skipTextBox1)TextBox2.Focus();
}
但是这段代码不起作用。之后,我在MSDN上找到了:
不要试图在Enter,GotFocus,Leave,LostFocus,Validating或Valid事件处理程序。
所以我怎么能这样做呢?
推迟执行Focus()方法,直到事件完成执行。使用Control.BeginInvoke()方法优雅地完成。像这样:
pre prerivate $ {textBox2_Enter(object sender,EventArgs e){
this.BeginInvoke((MethodInvoker)delegate {textBox3.Focus();});
}
I have a textbox and in some cases in Enter event I need to set the focus to a different textbox.
I tried that code:
private void TextBox1_Enter(object sender, EventArgs e)
{
if(_skipTextBox1) TextBox2.Focus();
}
But this code doesn't work. After that I found on MSDN:
Do not attempt to set focus from within the Enter, GotFocus, Leave, LostFocus, Validating, or Validated event handlers.
So how can I do it other way?
Postpone executing the Focus() method until after the event is finished executing. Elegantly done by using the Control.BeginInvoke() method. Like this:
private void textBox2_Enter(object sender, EventArgs e) {
this.BeginInvoke((MethodInvoker)delegate { textBox3.Focus(); });
}
这篇关于在Enter事件中设置焦点的替代方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!