Winforms 窗口窗体关闭事件

Winforms 窗口窗体关闭事件,winforms,Winforms,我正在使用C#创建一个窗口表单应用程序。其中我正在使用MDI接口 但我想这样做: private void Earnings_Leave(object sender, EventArgs e) { DialogResult result = MessageBox.Show("Are you sure to Quite this form","confirmation Message", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

我正在使用C#创建一个窗口表单应用程序。其中我正在使用MDI接口

但我想这样做:

private void Earnings_Leave(object sender, EventArgs e)
{
    DialogResult result = MessageBox.Show("Are you sure to Quite this form","confirmation Message", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

    if(result==DialogResult.Yes)
    {
       this.Close();
    }
    else if (result == DialogResult.No)
    {
       Earnings sibling = new Earnings();
       sibling.MdiParent = this.MdiParent;
       sibling.Show();
    }
}

但这不起作用。表单在两种情况下都将关闭。请帮助我。

您的代码看起来正确,但是WinForms在遇到错误时会自动关闭。 您必须确保关闭的原因是DialogResult

请使用以下内容更改代码部分:

private void Earnings_Leave(object sender, EventArgs e)
{
    DialogResult result = MessageBox.Show("Are you sure to Quite this form","confirmation Message", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

    if(result==DialogResult.Yes)
    {
 MessageBox.Show("You selected Yes", "Yes Message", MessageBoxButtons.OK);
       this.Close();
    }
    else if (result == DialogResult.No)
    {
 MessageBox.Show("You selected No", "No Message", MessageBoxButtons.OK);
       Earnings sibling = new Earnings();
       sibling.MdiParent = this.MdiParent;
       sibling.Show();
    }
}
如果看到对话框,您将知道代码是否正常工作