Easiest way to have a program minimize itself to the system tray using .NET 4

戏子无情 提交于 2019-11-28 17:51:00
LaGrandMere

Example in MSDN forum

Here's a quick example to show how to minimize to the notification area. You need to add references to the System.Window.Forms and System.Drawing assemblies.

public partial class Window1 : System.Windows.Window
{

    public Window1()
    {
        InitializeComponent();

        System.Windows.Forms.NotifyIcon ni = new System.Windows.Forms.NotifyIcon();
        ni.Icon = new System.Drawing.Icon("Main.ico");
        ni.Visible = true;
        ni.DoubleClick += 
            delegate(object sender, EventArgs args)
            {
                this.Show();
                this.WindowState = WindowState.Normal;
            };
    }

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

        base.OnStateChanged(e);
    }
}
Alex McBride

I've had success using this free notify-icon implementation in WPF.

http://www.hardcodet.net/projects/wpf-notifyicon

It's pretty simple to setup and the source code is provided. It doesn't rely on Windows Forms, so it's 'pure' WPF and very customizable.

You can find a tutorial on how to use it on CodeProject.
And here is the Nuget Package

Add notifyIcon to your App from Toolbox.
Select your main form >> go to the Properties >> select Events icon >> under FromClosing event type MainForm_FormClosing >> hit enter.

In opened .cs file enter following event action:

private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
     this.Hide();
     notifyIcon.Visible = true;
     ShowInTaskbar = false;
     e.Cancel = true;
}

Now your main FORM window will be minimized to the system tray when you click on X button. Next step is to get FORM back to normal state.
Go to the Properties of your notifyIcon >> find DoubleClick event >> type NotifyIcon_DoubleClick and hit enter to get event function created for you.

Put this code to your event:

private void NotifyIcon_DoubleClick(object sender, EventArgs e)
{
    this.Show();
    notifyIcon.Visible = false;
}

Now, if you want to make the notify icon in fancy style you can add context menu and link it to your notify icon, so you get something like that:

Here is where you link contextMenuStrip to NotifyIcon:

Good luck!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!