如果用户想要通过单击退出图标或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?",MessageBoxButtons.YesNo) == DialogResult.No) { e.Cancel = true; } }