c# - 调用子窗体的 Hide 方法后窗体失去焦点

标签 c# .net winforms

我的应用程序中有 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/

相关文章:

c# - 测量 Asp.Net MVC 应用程序请求/响应时间的准确方法

.net - System.Net.Mail 替代方案

c# - 如何使用 C#/WinForms 在运行时从 ComboBox 中删除项目

c# - 我将如何等待多个线程停止?

c# - 如何在 Windows 窗体应用程序的文本框中仅允许字母?

c# - 无法使用命名空间反序列化 XmlArray

C# "label.text"字符串转整数

c# - DataType 来存储和使用具有特定限制的通用类型?

c# - VSTO - 存储 Excel 工作簿设置的最佳位置

c# - Gritter Jquery 脚本