关闭表单时,会发生FormClosed
事件,并且我想在FormClosed
事件发生时进行一些工作,如:
this.FormClosed += (s, e) => {
var result = MessageBox.Show("Exit Program?", "Exit?", MessageBoxButtons.YesNo, MessageBoxIcons.Question);
if (result == DialogResult.No) {
return;
} else {
// Do some work such as closing connection with sqlite3 DB
Application.Exit();
}
};
问题在于,无论我在消息框中选择是或否,程序都会关闭。如果我选择不,我需要中止程序退出,所以我该怎么做?
答案 0 :(得分:7)
FormClosing
(而不是FormClosed
)事件的FormClosingEventArgs
包含Cancel
布尔值,您可以将其更改为true。请注意,即使您以编程方式关闭表单,也会发生这种情况。
this.FormClosing += (s, e) => {
var result = MessageBox.Show("Exit Program?", "Exit?", MessageBoxButtons.YesNo, MessageBoxIcons.Question);
if (result == DialogResult.No) {
e.Cancel = true;
} else {
// Do some work such as closing connection with sqlite3 DB
Application.Exit();
}
};
答案 1 :(得分:3)
您无法使用FormClosed
事件,您需要使用FormClosing
事件并将e.Cancel
设置为true
。
原因是表单关闭后发生FormClosed
事件,而表单关闭时发生FormClosing
事件。
FormClosingEventArgs
类包含一个名为Cancel
的布尔属性,您可以将其设置为true
以阻止表单关闭。