Подтвердить что ты не робот

Обнаружение причины закрытия формы

Как я могу определить, как закрывается форма окна? Например, как узнать, нажал ли пользователь кнопку, закрывающую форму, или если пользователь нажимает кнопку "X" в правом верхнем углу? Спасибо.

Update:

Забыл отметить, что кнопка вызывает метод Application.Exit().

4b9b3361

Ответ 1

Как уже упоминали башмоханды и Дмитрий Матвеев, решение должно быть FormClosingEventArgs. Но, как сказал Дмитрий, это не будет иметь никакого значения между вашей кнопкой и X в правом верхнем углу.

Чтобы различать эти два параметра, вы можете добавить логическое свойство ExitButtonClicked в вашу форму и установить его в true в кнопке Click-Event прямо перед вызовом Application.Exit().

Теперь вы можете задать это свойство в событии FormClosing и провести различие между этими двумя параметрами в случае UserClosing.

Пример:

    public bool UserClosing { get; set; }

    public FormMain()
    {
        InitializeComponent();

        UserClosing = false;
        this.buttonExit.Click += new EventHandler(buttonExit_Click);
        this.FormClosing += new FormClosingEventHandler(Form1_FormClosing);
    }

    void buttonExit_Click(object sender, EventArgs e)
    {
        UserClosing = true;
        this.Close();
    }

    void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        switch (e.CloseReason)
        {
            case CloseReason.ApplicationExitCall:
                break;
            case CloseReason.FormOwnerClosing:
                break;
            case CloseReason.MdiFormClosing:
                break;
            case CloseReason.None:
                break;
            case CloseReason.TaskManagerClosing:
                break;
            case CloseReason.UserClosing:
                if (UserClosing)
                {
                    //what should happen if the user hitted the button?
                }
                else
                {
                    //what should happen if the user hitted the x in the upper right corner?
                }
                break;
            case CloseReason.WindowsShutDown:
                break;
            default:
                break;
        }

        // Set it back to false, just for the case e.Cancel was set to true
        // and the closing was aborted.
        UserClosing = false;
    }

Ответ 2

Вы можете проверить свойство CloseReason FormClosingEventArgs в обработчике события FormClosing, чтобы проверить некоторые из возможных случаев. Однако описанные вами случаи будут неотличимы, если вы будете использовать это свойство. Вам нужно будет написать дополнительный код в обработчике событий клика вашей кнопки "закрыть", чтобы сохранить некоторую информацию, которая будет проверяться в обработчике события FormClosing, чтобы различать эти случаи.

Ответ 3

Вам нужно добавить слушателя в Even FormClosing, который отправляет в событие args свойство типа CloseReason, которое является одним из этих значений

    // Summary:
//     Specifies the reason that a form was closed.
public enum CloseReason
{
    // Summary:
    //     The cause of the closure was not defined or could not be determined.
    None = 0,
    //
    // Summary:
    //     The operating system is closing all applications before shutting down.
    WindowsShutDown = 1,
    //
    // Summary:
    //     The parent form of this multiple document interface (MDI) form is closing.
    MdiFormClosing = 2,
    //
    // Summary:
    //     The user is closing the form through the user interface (UI), for example
    //     by clicking the Close button on the form window, selecting Close from the
    //     window control menu, or pressing ALT+F4.
    UserClosing = 3,
    //
    // Summary:
    //     The Microsoft Windows Task Manager is closing the application.
    TaskManagerClosing = 4,
    //
    // Summary:
    //     The owner form is closing.
    FormOwnerClosing = 5,
    //
    // Summary:
    //     The System.Windows.Forms.Application.Exit() method of the System.Windows.Forms.Application
    //     class was invoked.
    ApplicationExitCall = 6,
}