我有两个按钮WinForm
(C#
File -Close和Red X)。我希望它们的行为方式相同,因此我创建了一个辅助方法,当两个不同的事件被触发时会调用它。这是我到目前为止所拥有的。
private void CloseFileOperation(object e)
{
// If the user selected the exit buttton from the main title bar,
// then handle the closing event properly.
if (e is FormClosingEventArgs)
{
FormClosingEventArgs FormCloser = (FormClosingEventArgs)e;
// If the Spreadsheet has been changed since the user opened it and
// the user has requested to Close the window, then prompt them to Save
// the unsaved changes.
if (SpreadSheet.Changed)
{
DialogResult UserChoice = MessageBox.Show("Would you like to save your changes?", "Spreadsheet Utility",
MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning);
switch (UserChoice)
{
case DialogResult.Yes:
SaveFileOperation();
FormCloser.Cancel = false;
break;
case DialogResult.No:
FormCloser.Cancel = false;
break;
case DialogResult.Cancel:
FormCloser.Cancel = true;
return;
}
}
// If the Spreadsheet hasn't been changed since the user opened it, then
// simply Close the window.
else
FormCloser.Cancel = false;
}
// Otherwise the user must have selected the "Close" option from the File menu.
// Handle the event in the following manner.
else
{
// If the Spreadsheet has been changed since the user opened it and
// the user has requested to Close the window, then prompt him to Save
// the unsaved changes.
if (SpreadSheet.Changed)
{
DialogResult UserChoice = MessageBox.Show("Would you like to save your changes?", "Spreadsheet Utility",
MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning);
switch (UserChoice)
{
case DialogResult.Yes:
SaveFileOperation();
this.Close();
break;
case DialogResult.No:
this.Close();
break;
case DialogResult.Cancel:
return;
}
}
// If the Spreadsheet hasn't been changed since the user opened it, then
// simply Close the window.
else
this.Close();
}
}
当用户选择Red X & File-Close选项时,我会调用此函数。请注意,当用户选择 File-Close 时,相应的操作会调用Close()操作,而该操作又会调用关闭事件。因此,警告对话框“您想保存您的更改”会显示两次。
有没有一种简单的方法可以做到这一点,类似于我目前的做法,可以消除窗口显示两次?