关闭按钮无法正确关闭表单

she*_*rin 0 c# datagridview winforms

我的表单包含一个button名为close。我只是将下面的代码放在关闭按钮中,单击...然后第二个代码集用于表单关闭。但是,如果我执行此当我点击close button 一个MessageBox会出现。当我单击“是”按钮时,该窗体未关闭,但是如果我第二次单击了“是”按钮,则该窗体将关闭。是什么原因?你能帮我么?

private void btnClose_Click(object sender, EventArgs e)
{
    if (MessageBox.Show("Are You Sure You Want To Close This Form?", 
                        "Close Application", 
                         MessageBoxButtons.YesNo) == DialogResult.Yes)
    {
        // MessageBox.Show("The application has been closed successfully.", 
        //                 "Application Closed!", 
        //                  MessageBoxButtons.OK);
        System.Windows.Forms.Application.Exit();
    }
    else
    {
        this.Activate();
    }
}

-------------------------------------   

private void frminventory_FormClosing(object sender, FormClosingEventArgs e)
{
    if (MessageBox.Show("Are You Sure You Want To Close This Form?", 
                        "Close Application", 
                         MessageBoxButtons.YesNo) == DialogResult.Yes)
    {
        System.Windows.Forms.Application.Exit();
    }
    else
    {
        this.Activate();
    }
}
Run Code Online (Sandbox Code Playgroud)

Dmi*_*nko 6

不要关闭/退出Application,但Form

private void btnClose_Click(object sender, EventArgs e) {
  // On btnClose button click all we should do is to Close the form
  Close();
}

private void frminventory_FormClosing(object sender, FormClosingEventArgs e) {
  // If it's a user who is closing the form...
  if (e.CloseReason == CloseReason.UserClosing) {
    // ...warn him/her and cancel form closing if necessary
    e.Cancel = MessageBox.Show("Are You Sure You Want To Close This Form?", 
                               "Close Application", 
                                MessageBoxButtons.YesNo) != DialogResult.Yes;
  }
}
Run Code Online (Sandbox Code Playgroud)

编辑:通常,我们向用户提出直接问题不清楚,如果我只是“关闭此表单”,会发生什么错误的事情),例如

private void frminventory_FormClosing(object sender, FormClosingEventArgs e) {
  // Data has not been changed, just close without pesky questions
  if (!isEdited)
    return;

  // If it's a user who is closing the form...
  if (e.CloseReason == CloseReason.UserClosing) {
    var action = MessageBox.Show(
      "You've edited the data, do you want to save it?"
       Text, // Let user know which form asks her/him
       MessageBoxButtons.YesNoCancel);

    if (DialogResult.Yes == action)
      Save(); // "Yes" - save the data edited and close the form
    else if (DialogResult.No == action)
      ;       // "No"  - discard the edit and close the form
    else
      e.Cancel = true; // "Cancel" - do not close the form (keep on editing) 
  }
}
Run Code Online (Sandbox Code Playgroud)