Free Information Technology Magazines and eBooks

Saturday, June 20, 2009

C#: How to minimize windows form to system tray

If we want our application to minimize to system tray, we can use of the WindowState Property of the form. WindowState gets or sets a value that indicates whether a window is restored, minimized, or maximized. Then to inform user that the application was minimized to system tray we can consume the NotifyIcon control to handle it. On this article, I will try to show you a sample project to implement the topic.


To minimize windows form to system tray, follow these steps.
1. Create your new C# project.
2. From the toolbox, drag the NotifyIcon to your form.
3. On your Form_Load event, copy and paste the following code:


private void Form1_Load(object sender, EventArgs e)
{
notifyIcon1.BalloonTipText = "This application was minimized to tray";
notifyIcon1.BalloonTipTitle = "My Sample Application";

//Display the Notify Baloon for 1 second
notifyIcon1.ShowBalloonTip(1000);

//Set the WindowState in Minimized Mode
WindowState = FormWindowState.Minimized;
}


4. Then on Form_Resize event, add this code.



private void Form1_Resize(object sender, EventArgs e)
{
//On minimize mode, show the form in System Tray only
if (FormWindowState.Minimized == WindowState)
{
Hide();
}
}


5. Now to restore the form upon double-click on NotifyIcon control.



private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
//Display the Form in normal state
WindowState = FormWindowState.Normal;
Show();
}


The sample project I used on this article was tested in Visual Studio 2008.

For more coding tips & tricks, subscribe now.

4 comments:

Anonymous said...

thanks mate

Andreas said...

Hallo,is
here Tray Icon example

Anonymous said...

buddy, it fails in Windows 7

Anonymous said...

Works fine. Also in Windows 7. Thanks for the article.