C# 如何在wpf表单中捕获窗口关闭按钮(窗口右上角的红色X按钮)事件?
如何在WPF表单中捕获窗口关闭按钮(窗口右上角的红色X按钮)事件?我们得到了关闭事件,窗口卸载事件,但如果他单击WPF表单的关闭按钮,我们希望显示一个弹出窗口。使用窗口中的C# 如何在wpf表单中捕获窗口关闭按钮(窗口右上角的红色X按钮)事件?,c#,wpf,vb.net,events,C#,Wpf,Vb.net,Events,如何在WPF表单中捕获窗口关闭按钮(窗口右上角的红色X按钮)事件?我们得到了关闭事件,窗口卸载事件,但如果他单击WPF表单的关闭按钮,我们希望显示一个弹出窗口。使用窗口中的关闭事件,您可以这样处理它以防止它关闭: private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) { e.Cancel = true; } 如果在form2 do action中按下确认按钮,如果按下X按钮
关闭事件,您可以这样处理它以防止它关闭:
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
e.Cancel = true;
}
如果在form2 do action中按下确认按钮,如果按下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;
}
解决方案:
有一个标志来标识是否从X图标按钮以外的位置调用Close()方法。(例如:IsNonCloseButtonClicked;)
在Closing()中有一个条件语句事件方法,用于检查IsNonCloseButtonClicked是否为false
如果为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
}
}
试试这个:
protected override void OnClosing(CancelEventArgs e)
{
this.Visibility=Visibility.Hidden;
string msg=“是否关闭?”;
MessageBoxResult结果=
MessageBox.Show(
味精,
“警告”,
MessageBoxButton.YesNo,
MessageBoxImage.Warning);
if(result==MessageBoxResult.No)
{
//如果用户不想关闭,请取消关闭
e、 取消=真;
}
其他的
{
e、 取消=假;
}
}
那么如果您在关闭事件中做了什么,您尝试了什么吗?我需要将所有关闭处理程序都添加到相应窗口的XAML:
请记住,当您从代码隐藏中调用this.Close()
时,此事件也会触发。