c# - 在 Enter 事件中设置焦点的替代方法

标签 c# winforms focus

我有一个文本框,在某些情况下,在 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/

相关文章:

c# - 限制在 C# 中使用结构

c# - 从 XML 更新插入 SQL Server 表

c# - 如何将组合框的选定值转换为整数?

javascript - 更改单选后如何聚焦于输入字段?

c# - 为什么我会收到此错误 : The ConnectionString property has not been initialized

c# - 确保特定线程接下来运行(获取资源)?

c# - 在两个文本框之间检查

vb.net - 主用户界面窗口未更新控件-跨线程操作无效

javascript - Google Chrome 重复 JavaScript 'focus' 事件

java - 如何在鼠标按下事件之前发送焦点丢失事件?