我如何在wpf中执行此操作
VB.NET
Private Sub FrmSettings_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
e.Cancel = (e.CloseReason = Forms.CloseReason.UserClosing)
Me.Hide()
End Sub
C#
private void FrmSettings_FormClosing(object sender, System.Windows.Forms.FormClosingEventArgs e)
{
e.Cancel = (e.CloseReason == Forms.CloseReason.UserClosing);
this.Hide();
}
因为wpf的关闭事件只给我e.Cancel而没有关闭理由:(
答案 0 :(得分:6)
我要感谢Bob King的提示并将其代码添加为C#WPF。这个对我有用。我的应用程序是一个托盘图标类型。在后面的WPF XAML表单代码中:
protected override void OnInitialized(EventArgs e)
{
base.OnInitialized(e);
Application.Current.ShutdownMode = System.Windows.ShutdownMode.OnMainWindowClose;
}
private bool m_isExplicitClose = false;// Indicate if it is an explicit form close request from the user.
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
base.OnClosing(e);
if (m_isExplicitClose == false)//NOT a user close request? ... then hide
{
e.Cancel = true;
this.Hide();
}
}
private void OnTaskBarMenuItemExitClick(object sender, RoutedEventArgs e)
{
m_isExplicitClose = true;//Set this to unclock the Minimize on close
this.Close();
}
答案 1 :(得分:5)
WPF的默认实现中没有等效项。您可以使用Windows钩子来获取原因。
以下帖子详细说明了如何执行此操作:http://social.msdn.microsoft.com/forums/en-US/wpf/thread/549a4bbb-e77b-4c5a-b724-07996774c60a/
答案 2 :(得分:5)
我不确定我理解WinForms方法解决了什么。
总是这样做是不是更好:
Protected Overrides Sub OnClosing(ByVal e As System.ComponentModel.CancelEventArgs)
e.Cancel = True
Me.Hide()
End Sub
然后在你的应用程序中设置它?
Application.Current.ShutdownMode = System.Windows.ShutdownMode.OnMainWindowClose
这样,无论何时你的孩子窗户关闭,你都可以将它们放在一边以便以后更快地显示,但是当主窗口关闭时你的应用程序仍会关闭(即退出,关机等)。