我的应用程序中有 Form1 使用 ShowDialog() 方法调用另一个表单 - Form2。经过一些用户交互后,Form2 调用其 Hide() 方法。之后,我的应用程序有时会失去焦点,有时不会。这可能是一些设计错误。
代码摘录:
public class Form1 : Form
{
Form2 form2;
public void SomeMethod()
{
if (form2==null) form2 = new Form2();
DialogResult result = form2.ShowDialog(this);
}
}
public class Form2 : Form
{
public Form2()
{
this.FormClosing += new FormClosingEventHandler(Form2_FormClosing);
}
void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing)
{
e.Cancel = true;
Hide();
}
}
}
编辑: 我的在线代码有错误
DialogResult result = form2.ShowDialog(this);
曾经
DialogResult result = ShowDialog(form2,this);
最佳答案
如果您隐藏该对话框,则 Form1 仍将无法访问,因为 ShowDialog 要求您在返回焦点之前将其关闭。
仅当您打算使用 Form2 执行某些操作时才处理 Form2 的关闭。否则就让对话框关闭,隐藏它没有任何好处。
参见 MSDN Form.ShowDialog了解更多详情。
代码示例
public class Form1: Form
{
private Form2: form2;
private bool doDbQuery;
public Form1()
{
doDbQuery = true;
}
public void SomeMethod()
{
if (form2 != null)
{
form2 = new Form();
}
if (doDbQuery)
{
// do DB query
// take a note of the information you retrieve
doDbQuery = false;
}
// pass this information to Form2 for it to display.
DialogResult result = form2.Execute(...);
}
}
public class Form2 : Form
{
public Form2()
{
}
public DialogResult Execute(...)
{
// use the execute method to inject the data you require for the form
return ShowDialog;
}
}
关于c# - 调用子窗体的 Hide 方法后窗体失去焦点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1888186/