C# 使用WPF最小化/关闭系统托盘的应用程序

C# 使用WPF最小化/关闭系统托盘的应用程序,c#,wpf,system-tray,C#,Wpf,System Tray,当用户最小化或关闭表单时,我想在系统托盘中添加应用程序。我是为这个案子做的。有谁能告诉我,当我关闭表单时,如何保持我的应用程序运行并将其添加到系统托盘中 public MainWindow() { InitializeComponent(); System.Windows.Forms.NotifyIcon ni = new System.Windows.Forms.NotifyIcon(); ni.Icon = new System.Dra

当用户最小化或关闭表单时,我想在系统托盘中添加应用程序。我是为这个案子做的。有谁能告诉我,当我关闭表单时,如何保持我的应用程序运行并将其添加到系统托盘中

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);
    }

您不需要使用
OnStateChanged()
。相反,请使用
PreviewClosed
事件

public MainWindow()
{
    ...
    PreviewClosed += OnPreviewClosed;
}

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

您还可以覆盖
onclose
,以保持应用程序运行,并在用户关闭应用程序时将其最小化到系统托盘中

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);
    }
}

我建议您:@Ammar现在已修复,构造函数不应接受任何参数