使用 WPF 最小化/关闭系统托盘的应用程序 [英] Minimizing/Closing Application to system tray using WPF

查看:53
本文介绍了使用 WPF 最小化/关闭系统托盘的应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to add application in System Tray when user minimize or close the form. I have done it for the Minimize case. Can anyone tell me that how i can keep my app running and add it into System Tray when I close the form?

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

推荐答案

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

You can also override OnClosing to keep the app running and minimize it to the system tray when a user closes the application.

>

MainWindow.xaml.cs

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

这篇关于使用 WPF 最小化/关闭系统托盘的应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆