Start Net Framework Application in System Tray

[Jul 18, 2010]


When an application start in system tray, the main window will not be shown until the user click on the system tray icon or launch the application again using the shortcut. Below is the source code that need to be implemented.

First, create a class that derived from ApplicationContext.

class VWgetAppContext : ApplicationContext
{
    public VWgetAppContext(MainForm mainForm)
    {
        Application.ApplicationExit += new EventHandler(OnApplicationExit);
        mainForm.FormClosed += new FormClosedEventHandler(OnFormClosed);

        if (!Util.StartInTray)
        {
            mainForm.Show();
        }
    }

    void OnApplicationExit(object sender, EventArgs e)
    {
    }

    void OnFormClosed(object sender, EventArgs e)
    {
        ExitThread();
    }
}

Then, create and run the main form in the application Main function.

///
/// The main entry point for the application.
///
[STAThread]
static void Main(string[] args)
{
    //...
    Util.MainForm = new MainForm();
    Application.Run(new VWgetAppContext(Util.MainForm));
    //...
}


Home
Web Log
Contact Me
© 2008-2012 Khomsan Phongphisansakun
May 19th, 2012