【发布时间】:2012-02-16 16:43:42
【问题描述】:
如何在 WPF 表单中捕获窗口关闭按钮(窗口右上角的红色 X 按钮)的事件?我们有关闭事件,也有窗口卸载事件,但是如果他单击 WPF 表单的关闭按钮,我们希望显示一个弹出窗口。
【问题讨论】:
-
那么如果你在Closing事件中做了什么会发生什么,你有没有尝试过?
如何在 WPF 表单中捕获窗口关闭按钮(窗口右上角的红色 X 按钮)的事件?我们有关闭事件,也有窗口卸载事件,但是如果他单击 WPF 表单的关闭按钮,我们希望显示一个弹出窗口。
【问题讨论】:
在Window中使用Closing事件,可以这样处理,防止关闭:
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
e.Cancel = true;
}
【讨论】:
<Window [...] Closing="myWindow_Closing">
this.Close() 时,也会触发此事件。
解决方案:
有一个标志来识别是否从 X 图标按钮以外的地方调用 Close() 方法。 (例如:IsNonCloseButtonClicked;)
在 Closing () 事件方法中有一个条件语句,用于检查 IsNonCloseButtonClicked 是否为假。
如果为 false,则应用程序正在尝试通过 X 图标按钮以外的方式关闭自身。如果为 true,则表示单击 X 图标按钮以关闭此应用。
[示例代码]
private void buttonCloseTheApp_Click (object sender, RoutedEventArgs e) {
IsNonCloseButtonClicked = true;
this.Close (); // this will trigger the Closing () event method
}
private void MainWindow_Closing (object sender, System.ComponentModel.CancelEventArgs e) {
if (IsNonCloseButtonClicked) {
e.Cancel = !IsValidated ();
// Non X button clicked - statements
if (e.Cancel) {
IsNonCloseButtonClicked = false; // reset the flag
return;
}
} else {
// X button clicked - statements
}
}
【讨论】:
如果按下form2中的确认按钮,则执行操作,如果按下X按钮则不执行任何操作:
public class Form2
{
public bool confirm { get; set; }
public Form2()
{
confirm = false;
InitializeComponent();
}
private void Confirm_Button_Click(object sender, RoutedEventArgs e)
{
//your code
confirm = true;
this.Close();
}
}
第一种形式:
public void Form2_Closing(object sender, CancelEventArgs e)
{
if(Form2.confirm == false) return;
//your code
}
【讨论】:
在 VB.NET 中:
Private Sub frmMain_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
' finalize the class
End Sub
禁用 Form X 按钮:
'=====================================================
' Disable the X button on the control bar
'=====================================================
Private Const CP_NOCLOSE_BUTTON As Integer = &H200
Protected Overloads Overrides ReadOnly Property CreateParams() As CreateParams
Get
Dim myCp As CreateParams = MyBase.CreateParams
myCp.ClassStyle = myCp.ClassStyle Or CP_NOCLOSE_BUTTON
Return myCp
End Get
End Property
【讨论】:
在 form1.Designer.cs 输入下面的代码来分配事件
this.Closing += Window_Closing;
在form1.cs放关闭函数
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
//change the event to avoid close form
e.Cancel = true;
}
【讨论】:
试试这个:
protected override void OnClosing(CancelEventArgs e)
{
this.Visibility = Visibility.Hidden;
string msg = "Close or not?";
MessageBoxResult result =
MessageBox.Show(
msg,
"Warning",
MessageBoxButton.YesNo,
MessageBoxImage.Warning);
if (result == MessageBoxResult.No)
{
// If user doesn't want to close, cancel closure
e.Cancel = true;
}
else
{
e.Cancel = false;
}
}
【讨论】: