How to override closing control in Windows Form c#

2019-09-22 04:18发布

I would like to make X control closing window to hide current display previous form.

In form1 I got:

private void button1_Click(object sender, EventArgs e)
{
    Form2 form2 = new Form2();
    form2.Tag = this;
    form2.Show(this);
    Hide();
}

and then when I click X I would like to show previous and hide the current.

3条回答
兄弟一词,经得起流年.
2楼-- · 2019-09-22 04:37

You have to keep track of your instanced forms.

// Program.cs

public static FormA Instance;

public static void Main()
{
    Instance = new FormA();
    Instance.Show();
}

Then:

// FormB.cs

private void button1_Click(object sender, EventArgs e)
{
    Hide(); // Hide current...
    Program.Instance.Show(); // Show previous...
}
查看更多
Root(大扎)
3楼-- · 2019-09-22 04:50

You can override OnFormClosing to do this.

 protected override void OnFormClosing(FormClosingEventArgs e)
{
    if (e.CloseReason == CloseReason.WindowsShutDown) return;

    // DO WHATEVER HERE
}
查看更多
倾城 Initia
4楼-- · 2019-09-22 04:53

You should not override Form.OnFormClosing() for just this. The Form.FormClosing event provides this functionality for you:

void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
  // Prevent the user from closing this window, minimize instead.
  if (e.CloseReason == CloseReason.UserClosing)
  {
    this.WindowState = FormWindowState.Minimized;
    e.Cancel = true;
  }
}
查看更多
登录 后发表回答