如果用户想通过单击退出图标或按 ALT+F4 退出应用程序,我想制作一个对话框询问用户是否真的确定要退出。
如何在应用程序实际关闭之前捕获此事件?
最佳答案
查看 OnClosing表单事件。
以下是该链接的摘录,实际上检查文本字段上的更改并提示保存:
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
// Determine if text has changed in the textbox by comparing to original text.
if (textBox1.Text != strMyOriginalText)
{
// Display a MsgBox asking the user to save changes or abort.
if(MessageBox.Show("Do you want to save changes to your text?", "My Application",
MessageBoxButtons.YesNo) == DialogResult.Yes)
{
// Cancel the Closing event from closing the form.
e.Cancel = true;
// Call method to save file...
}
}
}
您可以更改文本以满足您的需要,然后我认为您可能希望根据您的文本将 DialogResult.Yes
切换为 DialogResult.No
。
这里是一些专门为您修改的代码:
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if(MessageBox.Show("Are you sure you want to quit?", "My Application", MessageBoxButtons.YesNo) == DialogResult.No)
{
e.Cancel = true;
}
}
关于c# - 如何捕获退出 Winforms 应用程序的事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11047475/