WPF关闭时如何隐藏?

5

如何在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 的 Close 事件只提供了 e.Cancel 而没有提供关闭原因 :(
3个回答

7

我想感谢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();
}

2
这样关闭程序时,通过任务管理器或在Windows注销时将导致程序崩溃。 - Poma

6

7
多难看啊,什么都没建造 :( - Peter

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

这样,每当您的子窗口关闭时,您都可以将它们保留下来以便稍后更快地显示,但是当主窗口关闭时(即退出、关闭等),您的应用程序仍会关闭。


这样做将不会通过任务管理器或Windows注销关闭。此外,在这种情况下,您无法在退出时保存应用程序数据。 - Poma
我不确定我理解你的意思@Poma... 你可以重写应用程序的OnExit方法来处理退出时保存数据等。 - Bob King
如果我关闭Windows应用程序,OnExit方法将永远不会被调用,因为取消关闭事件将防止应用程序关闭。最终,Windows将只是杀死该进程。 - Poma
这绝对不是真的。你有一些额外的更改超出了这个基本情况,导致你的应用程序无法干净地退出。你是否正确标记了主窗口?你的主窗口在关闭时不可见吗?我的解决方案在我们的应用程序中可靠且干净。 - Bob King

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接