我如何在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并没有closereason :(
我要感谢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(); }
WPF的默认实现中没有等效项.您可以使用Windows钩子来获取原因.
以下文章详细说明了如何执行此操作:http://social.msdn.microsoft.com/forums/en-US/wpf/thread/549a4bbb-e77b-4c5a-b724-07996774c60a/
我不确定我理解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
这样,无论何时您的孩子窗户关闭,您都可以将它们保持在一起以便以后更快地显示,但是当主窗口关闭时(即退出,关机等),您的应用仍会关闭.