【问题标题】:Minimizing/Closing Application to system tray using WPF使用 WPF 最小化/关闭应用程序到系统托盘
【发布时间】:2015-01-31 15:03:37
【问题描述】:

当用户最小化或关闭表单时,我想在系统托盘中添加应用程序。我已经为最小化案例做到了。谁能告诉我,当我关闭表单时,如何让我的应用程序继续运行并将其添加到系统托盘中?

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

【问题讨论】:

标签: c# wpf system-tray


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    您还可以覆盖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);
        }
    }
    

    【讨论】:

    • @Ammar 现在已修复,构造函数不应接受任何参数
    猜你喜欢
    • 1970-01-01
    • 2011-11-29
    • 1970-01-01
    • 2012-11-17
    • 1970-01-01
    • 1970-01-01
    • 2017-11-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多