当我按Alt + F4时,我的应用程序正在关闭。如何在退出前让MessageBox首先显示确认,如果No是响应,applcation将不会继续关闭?
答案 0 :(得分:5)
除了已在此处发布的答案外,不要成为挂起整个系统的傻瓜:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason != CloseReason.UserClosing)
{
e.Cancel = false;
return;
}
// other logic with Messagebox
...
}
答案 1 :(得分:3)
处理Form.Closing
事件,该事件以CancelEventArgs
为参数。在该处理程序中,显示您的消息框。如果用户希望取消,请将事件参数的属性.Cancel
设置为true
,如下所示:
private void Form1_Closing(object sender, CancelEventArgs e)
{
var result = MessageBox.Show("Do you really want to exit?", "Are you sure?", MessageBoxButtons.YesNo);
if (result == DialogResult.No)
{
e.Cancel = true;
}
}
答案 2 :(得分:0)
在FormClosing() event上添加以下代码:
private void MyForm_Closing(object sender, CancelEventArgs e)
{
if(MessageBox.Show("Are you sure want to exit the App?", "Test", MessageBoxButtons.YesNo) == DialogResult.No)
{
e.Cancel = true;
}
}