0

我知道即使在 StackOverflow 中也有类似问题的示例,但我很难理解问题的性质,因此 - 解决我的自定义案例。

我现在拥有的是这段代码:

bool closingPending = false;
private void MyFormN_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (closingPending) return;
            //DialogResult answer = MessageBox.Show("Do you want to save changes ?", "Save",
            if (MessageBox.Show("Do you want to save changes ?", "Save",
                                   MessageBoxButtons.YesNoCancel,
                                   MessageBoxIcon.Information,
                                   MessageBoxDefaultButton.Button3) == DialogResult.Yes)
            {
                closingPending = true;
                MessageBox.Show("To Do - validate and save");
            }
            if (MessageBox.Show("Do you want to save changes ?", "Save",
                                   MessageBoxButtons.YesNoCancel,
                                   MessageBoxIcon.Information,
                                   MessageBoxDefaultButton.Button3) == DialogResult.Cancel)
            {
                closingPending = true;
                e.Cancel = true;
            }
            if (MessageBox.Show("Do you want to save changes ?", "Save",
                                   MessageBoxButtons.YesNoCancel,
                                   MessageBoxIcon.Information,
                                   MessageBoxDefaultButton.Button3) == DialogResult.No)
            {
                closingPending = true;
                 Application.Exit();
            }
        }

这是我的尝试和我从这里的其他帖子中获得的一些想法的结果。但是当我执行此代码时会发生什么 - 通过按下[x]窗口的 ,我会显示消息框,但无论我单击哪个按钮,表单都会显示多次。在添加之前closingPending,我很确定这个问题仅在我尝试时发生Application.Exit()。当我尝试这个例子时,这个closingPending例子起作用了:

if(closingPending) return;
if (MessageBox.Show("This application is closing down because of " + e.CloseReason.ToString() + ". Do you really want to close it ?", "", MessageBoxButtons.YesNo) == DialogResult.No)
    {                
        e.Cancel = true;
    }
    else
    {
        closingPending = true;
        Application.Exit();
    }

但是,我对导致问题的原因有所了解,但距离完全理解或解决它还有很长的路要走。

4

1 回答 1

2

试试下面的东西......它会解决你的问题......

DialogResult result = MessageBox.Show("Do you want to save changes ?", "Save",
                                   MessageBoxButtons.YesNoCancel,
                                   MessageBoxIcon.Information,
                                   MessageBoxDefaultButton.Button3);

            switch (result)
            {

                case DialogResult.Yes: 
                    closingPending = true;
                    MessageBox.Show("To Do - validate and save");
                    break;

                case DialogResult.No: 
                    closingPending = true;
                    Application.Exit();
                    break;

                case DialogResult.Cancel:
                    closingPending = true;
                    e.Cancel = true;
                    break;
            }
于 2013-01-28T15:54:24.653 回答