I followed the commonly-linked tip for reducing an application to the system tray : http://www.developer.com/net/csharp/article.php/3336751 Now it works, but there is still a problem : my application is shown when it starts ; I want it to start directly in the systray. I tried to minimize and hide it in the Load event, but it does nothing.
Edit : I could, as a poster suggested, modify the shortcut properties, but I'd rather use code : I don't have complete control over every computer the soft is installed on.
I don't want to remove it completely from everywhere except the systray, I just want it to start minimized.
Any ideas ?
Thanks
In your main program you probably have a line of the form:
Application.Run(new Form1());
This will force the form to be shown. You will need to create the form but not pass it to Application.Run
:
Form1 form = new Form1();
Application.Run();
Note that the program will now not terminate until you call Application.ExitThread()
. It's best to do this from a handler for the FormClosed
event.
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
Application.ExitThread();
}
If you are using a NotifyIcon
, try changing ShowInTaskbar to false.
To remove it from the Alt+Tab screen, try changing your window border style; I believe some of the tool-window styles don't appear...
something like:
using System;
using System.Windows.Forms;
class MyForm : Form
{
NotifyIcon sysTray;
MyForm()
{
sysTray = new NotifyIcon();
sysTray.Icon = System.Drawing.SystemIcons.Asterisk;
sysTray.Visible = true;
sysTray.Text = "Hi there";
sysTray.MouseClick += delegate { MessageBox.Show("Boo!"); };
ShowInTaskbar = false;
FormBorderStyle = FormBorderStyle.SizableToolWindow;
Opacity = 0;
WindowState = FormWindowState.Minimized;
}
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new MyForm());
}
}
If it still appears in the Alt+Tab, you can change the window styles through p/invoke (a bit hackier):
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
IntPtr handle = this.Handle;
int currentStyle = GetWindowLong(handle, GWL_EXSTYLE);
SetWindowLong(handle, GWL_EXSTYLE, currentStyle | WS_EX_TOOLWINDOW);
}
private const int GWL_EXSTYLE = -20, WS_EX_TOOLWINDOW = 0x00000080;
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern int SetWindowLong(IntPtr window, int index, int value);
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern int GetWindowLong(IntPtr window, int index);