简体   繁体   English

通过验证表单中单击的按钮来跟踪Windows表单的关闭事件

[英]Track closing event of windows form with validation of button clicked in the form

I have a form which contains a close button (there are many control in the form, but I am concerning about the close event) and a save button. 我有一个包含关闭按钮的表单(表单中有很多控件,但是我关心的是close事件)和一个保存按钮。

If a form have value in certain text box (say TextBox1), 如果表单在某些文本框中具有值(例如TextBox1),

Then I want to validate that the save button is clicked before closing the form (whether close button or the 'X' button at top is pressed). 然后,我想在关闭表单之前验证是否单击了保存按钮(是否按下了关闭按钮或顶部的“ X”按钮)。

But if there is no value in that text box or the form is just initialized and user just want to close the form, it simply closes the form. 但是,如果在该文本框中没有任何值,或者表单只是初始化了,而用户只想关闭表单,则它只是关闭表单。 How to perform this validation. 如何执行此验证。

I would follow the pattern of 99% of windows applications: allow to close a window, but ask to save changes if there are any. 我将遵循99%的Windows应用程序的模式:允许关闭一个窗口,但是询问是否保存更改。 Here is a simple implementation of that pattern: 这是该模式的简单实现:

private bool _hasChanges;

private void textBox1_TextChanged(object sender, EventArgs e)
{
    this._hasChanges = true;
}

private void form_FormClosing(object sender, FormClosingEventArgs e)
{
    if (this._hasChanges)
    {
        var dialogResult = MessageBox.Show("Save changes?", "Confirm", MessageBoxButtons.YesNoCancel);
        switch (dialogResult)
        {
            case DialogResult.Yes:
                this.Save();
                break;
            case DialogResult.No:
                this._hasChanges = false;
                break;
        }
        e.Cancel = this._hasChanges;
    }
}

private void Save()
{
    // Save
    this._hasChanges = false;
}

private void buttonSave_Click(object sender, EventArgs e)
{
    this.Save();
}

private void buttonOk_Click(object sender, EventArgs e)
{
    this.Close();
}

private void buttonCancel_Click(object sender, EventArgs e)
{
    this._hasChanges = false;
    this.Close();
}

The pivotal part is the boolean _hasChanges . 关键部分是布尔值_hasChanges If there are many controls that can cause changes this can be real pain. 如果有许多控件可能导致更改,则可能会很痛苦。 An alternative could be to use databinding to a class that implements INotifyPropertyChanged and subscribe to its PropertyChanged event. 一种替代方法是对实现INotifyPropertyChanged的类使用数据绑定并预订其PropertyChanged事件。

Tie into the Closing Event and use your EventHandler to validate that textbox. 绑定结束事件,并使用EventHandler验证该文本框。 Keep in mind that Closing occurs at the time the form is closing and (if memory servers correctly) there is a property on the eventarg that will let you cancel closing of the form. 请记住,关闭是在关闭表单时发生的,并且(如果内存服务器正确)在eventarg上有一个属性,可让您取消关闭表单。 This event is raised regardless of how the request is executed. 无论如何执行请求,都会引发此事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM