如何通过显示MessageBox
来阻止关闭窗口? (技术:WinForms
与C#
)
当发生关闭事件时,我希望运行以下代码:
private void addFile_FormClosing( object sender, FormClosingEventArgs e ) {
var closeMsg = MessageBox.Show( "Do you really want to close?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Question );
if (closeMsg == DialogResult.Yes) {
//close addFile form
} else {
//ignore closing event
}
}
答案 0 :(得分:93)
private void Form1_FormClosing(object sender, FormClosingEventArgs e) {
var window = MessageBox.Show(
"Close the window?",
"Are you sure?",
MessageBoxButtons.YesNo);
e.Cancel = (window == DialogResult.No);
}
答案 1 :(得分:26)
捕获FormClosing事件并设置e.Cancel = true
private void AdminFrame_FormClosing(object sender, FormClosingEventArgs e)
{
var res = MessageBox.Show(this, "You really want to quit?", "Exit",
MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
if (res != DialogResult.Yes)
{
e.Cancel = true;
return;
}
}
答案 2 :(得分:6)
在OnFormClosing
事件中,您可以显示对话框,if
答案为false(不显示),然后将Cancel
的{{1}}属性设置为{{1 }}
答案 3 :(得分:4)
一个特殊的转折可能是总是阻止用户关闭表单:
private void Frm_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = (e.CloseReason == CloseReason.UserClosing);
// disable user closing the form, but no one else
}
答案 4 :(得分:2)
为了在特定情况下阻止或阻止表单关闭,您可以使用此策略:
theano.function
答案 5 :(得分:1)
直接来自MSDN:
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...
}
}
}
在您的情况下,您无需执行任何操作即可明确关闭表单。除非您取消它,它将自动关闭,因此您的代码将是:
private void addFile_FormClosing( object sender, FormClosingEventArgs e ) {
var closeMsg = MessageBox.Show( "Do you really want to close?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Question );
if (closeMsg == DialogResult.Yes) {
// do nothing
} else {
e.Cancel = true;
}
}
答案 6 :(得分:0)
private void addFile_FormClosing( object sender, FormClosingEventArgs e ) {
var closeMsg = MessageBox.Show( "Do you really want to close?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Question );
if (closeMsg == DialogResult.Yes) {
e.Cancel = false;
} else {
e.Cancel = true;
}
e.Cancel是启用或禁用表单关闭事件。
例如,e.Cancel = true
将使您无法关闭。
答案 7 :(得分:0)
关闭表单时,您可以运行所需的任何代码,然后隐藏表单而不是关闭表单以防止其被处置
yourFormName.FormClosing += (s, e) =>
{
// any code you want
yourFormName.Hide(); // this hides the form
e.Cancel = true; // this cancels the close event, you can put any boolean exprission
};