У меня есть две кнопки на моем WinForm
в C#
(Файл-Закрыть & Красный X). Я бы хотел, чтобы оба они поступали одинаково, поэтому я создал вспомогательный метод, который вызывается при запуске двух разных событий. Вот что я до сих пор.Закрытие окон в WinForms
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 & Файл-Закрыть варианты. Обратите внимание, что когда пользователь выбирает «Закрыть-Закрыть» соответствующие вызовы действий в операции Close(), которая, в свою очередь, вызывает событие закрытия. В результате этого дважды отображается диалог с предупреждением «Хочешь сохранить изменения».
Есть ли простой способ сделать это, аналогично тому, как у меня есть это сейчас, что приведет к удалению окна, отображаемого дважды?
Можно ли назвать этот метод в случае FormClosing вместо в щелчками кнопки? Ответ Судхакара в основном тот, что я имел в виду, но он набрал его первым. – sab669