如何以wpf格式捕捉窗口关闭按钮(窗口右上角的红色X按钮)的事件?我们还有关闭事件,窗口卸载事件,但是如果他点击wpf表单的关闭按钮,我们想要显示一个弹出窗口。
请帮助。
答案 0 :(得分:31)
在窗口中使用Closing
事件,您可以像这样处理它以防止它关闭:
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
e.Cancel = true;
}
答案 1 :(得分:3)
如果按下,则表单2中的确认按钮执行操作,如果按下则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
}
答案 2 :(得分:0)
在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
要禁用表格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
答案 3 :(得分:0)
放在下面的代码中以分配事件
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;
}
答案 4 :(得分:0)
解决方案:
具有标志 ,以标识是否从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
}
}
答案 5 :(得分:0)
尝试一下:
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;
}
}