Кнопка Закрыть не закрывает форму должным образом - PullRequest
0 голосов
/ 20 марта 2019

Моя форма содержит 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();
    }
}

Ответы [ 2 ]

6 голосов
/ 20 марта 2019

Не закрывать / выходить 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;
  }
}

Редактировать: Обычно мы задаем прямых вопросов пользователю (это неясно , какие неправильные вещи могут возникнуть, если я просто "Закрыть эту форму" ), например

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) 
  }
}
0 голосов
/ 20 марта 2019

Итак, потому что я не могу комментировать, я бы сделал что-то вроде этого.

    //Create this variable
    private bool _saved = true;
    public Form1()
    {
        InitializeComponent();
    }

    private void btnSave_Click(object sender, EventArgs e)
    {
        DoSomething();
        _saved = true;
    }

    //Raised when the text is changed. I just put this for demonstration purpose.
    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        _saved = false;
    }

    private void btnClose_Click(object sender, EventArgs e)
    {
        Close();
    }

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (_saved == false)
        {
            var result = MessageBox.Show("Are you sure you want to close?\nYou may have unsaved information", "Information", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Information);
            if (result == DialogResult.Yes)
            {
                _saved = true;
                Application.Exit();
            }
            else
                e.Cancel = true;
        }
    }

Надеюсь, что это может решить вашу проблему

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...