C#中如何控制从这个最后打开另一个窗体的窗体?

How to control the form that opened another form from this last in C#?

我正在编写一段代码,当用户单击一个按钮时,会弹出一个子窗体并让用户输入信息。当子窗体出现时,父窗体被最小化。我希望在用户单击 x 按钮时返回父表单。我试图在 childform_FormClosed 事件中将 FormWindowState 属性 设置回正常状态,但子窗体关闭,而父窗体继续最小化。我正在使用 VS 社区 2019;我看到有人能够通过设计选项卡中的属性 window 访问表单关闭事件 属性,但我找不到它在我的 VS 版本中的位置,所以我写了这段代码在。我尝试了以下方法:

子形式:

private void ChildForm_FormClosed(object sender, FormClosingEventArgs e)
{
    ParentForm frm = (ParentForm)Application.OpenForms["ParentForm"];// find open form
    frm.WindowState = FormWindowState.Normal;
}

要获得简洁的设计,您应该使用表单创建器模式并像这样传递源表单:

ParentForm.cs

WindowState = FormWindowState.Minimized;
ChildForm.Create(this).ShowDialog();

ChildForm.cs

static public ChildForm Create(Form sender)
{
  ChildForm form = new ChildForm();
  form.Sender = sender;
  return form;
}

private Form Sender;

private void ChildForm_FormClosed(object sender, FormClosingEventArgs e)
{
    if (Sender != null)
      Sender.WindowState = FormWindowState.Normal;
}

你也可以封装更多:

ParentForm.cs

ChildForm.Run(this);

ChildForm.cs

static public void Run(Form sender, bool isDialog)
{
  if (sender != null)
    sender.WindowState = FormWindowState.Minimized;
  ChildForm form = new ChildForm();
  form.Sender = sender;
  if ( isDialog )
    form.ShowDialog();
  else
    form.Show();
}

private Form Sender;

private void ChildForm_FormClosed(object sender, FormClosingEventArgs e)
{
    if (Sender != null)
      Sender.WindowState = FormWindowState.Normal;
}

您可以在父级中注册 Closed 事件。这些也可以 'outside' 以其自身的形式提供。

例如:(伪代码)

public partial class FormParent : Form
{
    private FormChild _formChild;

    public void ButtonOpen_Click(object sender, EventArgs e)
    {
        // if the formChild already exists, don't create a new one.
        if(_formChild != null)
        {
            _formChild.BringToFront();
            return;
        }

        _formChild = new FormChild();
        _formChild.Closed += FormChildClosed;
        _formChild.Show();
        this.WindowState = FormWindowState.Minimized;
    }
 
    public void FormChildClosed(object sender, EventArgs e)
    {
        // don't forget to deregister the event, so the old FormChild can be garbage collected.
        _formChild.Closed -= FormChildClosed;
        _formChild = null;
        this.WindowState = FormWindowState.Normal;
    }
}

public partial class FormChild : Form
{
    public FormChild()
    {
        // do something
    }
}

这就是你问的,


这就是我的建议,使用阻止当前方法执行的 ShowModal。所以在方法之后,你可以继续做你想做的事情。

public partial class FormParent : Form
{
    private FormChild _formChild;

    public void ButtonOpen_Click(object sender, EventArgs e)
    {
        _formChild = new FormChild();
        this.WindowState = FormWindowState.Minimized;
        _formChild.ShowModal();
        this.WindowState = FormWindowState.Normal;
    }
}

public partial class FormChild : Form
{
    public FormChild()
    {
        // do something
    }
}