gpt4 book ai didi

c# - Control.Focus() 错误

转载 作者:行者123 更新时间:2023-11-30 21:01:20 25 4
gpt4 key购买 nike

我在使用 Form 控件聚焦时遇到了一些问题。

在 form1 上,我单击一个按钮并运行以下代码:

private void btnTest_Click(object sender, System.EventArgs e)
{
form2 = new Form2();

Application.Idle += new EventHandler(Application_Idle);

form2.Show();
form2.Activate();
form2.textBox1.Focus();

Form3 form3 = new Form3();
form3.ShowDialog();
}

然后,在此 CLR 之后,我运行事件 Application_Idle,在该事件上我添加了一个必须关注 textBox2 控件的方法。

private void Application_Idle(object sender, EventArgs e)
{
form2.textBox2.Focus();
form2.textBox2.Select();
form2.textBox2.Focus();

Application.Idle -= new EventHandler(Application_Idle);
}

但当我单击 form1 上的按钮时,我看到 Form2 显示,Form3 显示,然后 Application_Idle 方法引发,但 form2.textBox2 控件没有获得焦点。 ..

如果我注释掉 form3.ShowDialog(); 行,它工作正常,但我如何使用另一个表单激活来聚焦表单元素?(form3.ShowDialog()) ?

备注补充:问题还在于我有一个严格的架构,我只能更改 Application_Idle 方法。

最佳答案

您遇到的问题是 modality :

Forms and dialog boxes are either modal or modeless. A modal form or dialog box must be closed or hidden before you can continue working with the rest of the application.

Dialog boxes that display important messages should always be modal. The About dialog box in Visual Studio is an example of a modal dialog box. MessageBox is a modal form you can use.

Modeless forms let you shift the focus between the form and another form without having to close the initial form. The user can continue to work elsewhere in any application while the form is displayed.

当您使用 ShowDialog 时,显示的表单会阻止调用方返回控制权,直到对话框关闭。如果这不是您想要的效果,您可以使用 Show 方法。

关于c# - Control.Focus() 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14281739/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com