使用WPF将应用程序最小化/关闭到系统托盘

15

我希望在用户最小化或关闭窗体时将应用程序添加到系统托盘中。已实现最小化情况下的功能。请问如何在关闭窗体时保持应用程序运行并将其添加到系统托盘中?

public MainWindow()
    {
        InitializeComponent();
        System.Windows.Forms.NotifyIcon ni = new System.Windows.Forms.NotifyIcon();
        ni.Icon = new System.Drawing.Icon(Helper.GetImagePath("appIcon.ico"));
        ni.Visible = true;
        ni.DoubleClick +=
            delegate(object sender, EventArgs args)
            {
                this.Show();
                this.WindowState = System.Windows.WindowState.Normal;
            };
        SetTheme();
    }

    protected override void OnStateChanged(EventArgs e)
    {
        if (WindowState == System.Windows.WindowState.Minimized)
            this.Hide();
        base.OnStateChanged(e);
    }

1
我推荐你使用:https://visualstudiogallery.msdn.microsoft.com/aacbc77c-4ef6-456f-80b7-1f157c2909f7/ - Xaruth
2个回答

13

当用户关闭应用程序时,您还可以覆盖 OnClosing 方法,并将应用程序最小化到系统托盘以保持其运行。

MainWindow.xaml.cs

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    // Minimize to system tray when application is minimized.
    protected override void OnStateChanged(EventArgs e)
    {
        if (WindowState == WindowState.Minimized) this.Hide();

        base.OnStateChanged(e);
    }

    // Minimize to system tray when application is closed.
    protected override void OnClosing(CancelEventArgs e)
    {
        // setting cancel to true will cancel the close request
        // so the application is not closed
        e.Cancel = true;

        this.Hide();

        base.OnClosing(e);
    }
}

1
@Ammar,问题已经解决,构造函数不应该带任何参数。 - Agrejus

2
你不需要使用 OnStateChanged()。相反,使用 PreviewClosed 事件即可。
public MainWindow()
{
    ...
    PreviewClosed += OnPreviewClosed;
}

private void OnPreviewClosed(object sender, WindowPreviewClosedEventArgs e)
{
    m_savedState = WindowState;
    Hide();
    e.Cancel = true;
}

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