Minimise Form to System Tray on Close (.NET 2.0)
VB version here.
In previous versions minimising to the system tray instead of closing a form was a hassle. You had to mess about checking whether the system was shutting down, etc. or else your app would prevent Windows from ever closing. In .NET 2.0 that process is simplified consideralbly:
CSharp Code:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing)
{
// The user has requested the form be closed so mimimise to the system tray instead.
e.Cancel = true;
this.Visible = false;
this.notifyIcon1.Visible = true;
}
}
This will minimise the form to the system tray if the user requests the close by clicking the Close button on the title bar, selecting Close from the system menu, pressing Alt+F4 or performing some action that causes your code to call the form's Close method. All other reasons for closure, including calling Application.Exit or Windows shutting down, will cause the form to actually close.
Re: Minimise Form to System Tray on Close (.NET 2.0)
Here's a more thorough look at the different reasons a form could be closing:
CSharp Code:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
switch (e.CloseReason)
{
case CloseReason.ApplicationExitCall:
// The user perfromed an action that caused your code to call Application.Exit.
// You could go either way here but I'd suggest that you shouldn't be calling Application.Exit
// if you don't actually want the application to exit. In that case close the main form instead.
e.Cancel = false;
break;
case CloseReason.FormOwnerClosing:
// This form is a modeless dialogue, which you shouldn't be minimising to the system tray anyway.
e.Cancel = false;
break;
case CloseReason.MdiFormClosing:
// This form is an MDI child form, which you shouldn't be minimising to the system tray anyway.
e.Cancel = false;
break;
case CloseReason.None:
// If the reason can't be determined then something funky is going on so I'd suggest you let the form close.
e.Cancel = false;
break;
case CloseReason.TaskManagerClosing:
// The user pressed the End Task button on the Applications tab (NOT the Processes tab) of the Task Manager.
// You could go either way here too. It really depends on your app and if you don't want the user to be able to exit
// this way. I'd suggest letting the form close but there would definitely be legitimate reasons for preventing it.
e.Cancel = false;
break;
case CloseReason.UserClosing:
// The user clicked the Close button on the title bar, pressed Alt+F4, selected Close from the
// system menu or performed some action that caused your code to call the form's Close method.
// Don't let the form close.
e.Cancel = true;
this.Visible = false;
this.notifyIcon1.Visible = true;
break;
case CloseReason.WindowsShutDown:
// Windows is shutting down.
// Definitely let the form close or you'll prevent Windows shutting down normally.
e.Cancel = false;
break;
}
}