我有一个文本框,在某些情况下,在 Enter 事件中我需要将焦点设置到不同的文本框。
我尝试了该代码:
private void TextBox1_Enter(object sender, EventArgs e)
{
if(_skipTextBox1) TextBox2.Focus();
}
但是这段代码不起作用。之后我在MSDN上找到:
Do not attempt to set focus from within the Enter, GotFocus, Leave, LostFocus, Validating, or Validated event handlers.
那么我怎样才能用其他方式做到这一点?
最佳答案
推迟执行 Focus() 方法,直到事件执行完毕。通过使用 Control.BeginInvoke() 方法可以优雅地完成。像这样:
private void textBox2_Enter(object sender, EventArgs e) {
this.BeginInvoke((MethodInvoker)delegate { textBox3.Focus(); });
}
关于c# - 在 Enter 事件中设置焦点的替代方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4539074/