24 August, 2017

Minimize An App to System Tray

24-Aug-2017


I am writing a small WinForms program, and I thought of including minimize an app to system tray feature. Since this is the first time I will do this, I just did a search in Google. I am very sure many have done it as it already is a common feature.

Well, common for everybody else, but at this point, not me. Not yet.

Thus, I searched for ‘minimize an app to system tray’, and I did find valuable articles, many in Q&A forums, like StackOverflow.com.

I’ll go directly to the point now. What is required to make it happen?

1. Handle the form’s resize event.
2. Make a NotifyIcon click event restore the form back.

Here’s how it’s done.


Handle the Form’s Resize Event

Select the form and on its Events, declare this:

private void MyForm_Resize(object sender, EventArgs e) {
    if (FormWindowState.Minimized == this.WindowState) {
       myNotifyIcon.Visible = true;
       myNotifyIcon.ShowBalloonTip(500);
       this.Hide();
    }
    else if (FormWindowState.Normal == this.WindowState) {
       myNotifyIcon.Visible = false;
    }
}


Make a NotifyIcon Click Event Restore the Form Back

Add a NotifyIcon tool, and on its click event, declare this:

private void myNotifyIcon_Click(object sender, EventArgs e) {
    this.Show();
    this.WindowState = FormWindowState.Normal;
}


This is all that is required, really. But sometimes it doesn’t work. One small trick is needed.

Add an Icon to the NotifyIcon tool.

myNotifyIcon.Icon = SystemIcons.Application;

Also, you can add in the Text and Tip properties:

myNotifyIcon.BalloonTipText = "App is minimized to System Tray.";

myNotifyIcon.BalloonTipTitle = "My App Name";


Sometimes, you will see articles that suggest using the Form’s Visible property. But this is also known to still make the app appear or selectable (although not visible) when you do Alt + Tab. So stick to Hide() and Show() events. Still your choice, though.

Okay. I’ll stop here, cause that’s all that is really needed to minimize an app to system tray. Easy, right?

Happy coding!

No comments:

Post a Comment