Starting an application without showing a form

There were a lot of good comments/questions about keeping your UI responsive, if you're interested in threading/application contexts etc, it's worth a peek.

I thought I'd rehash something today I've already talked about, but it is buried in my how to build notify icon (system tray) applications article, and I think it's worthy of it's own coverage here: how to run an application without showing a form

Dissecting Application.Run

If you have created a Windows Forms application, you may have happened across this line in Main:

Application.Run(new Form1());

Magically, after calling this, the Form appears and events start firing left and right. Here’s what is actually happening, not quite so magically:  

//Taking a microscope to Application.Run –
//create the form, and call initialize component

Form1 form1 = new Form1();

// create an application context

ApplicationContext applicationContext = new ApplicationContext();

// Set applicationContext.MainForm so that
// when form1 closes, exit the application context

applicationContext.MainForm = form1;

// Call Application.Run which will
// - call applicationContext.MainForm.Show()
// - begin processing events
Application.Run(applicationContext);

From this code, we can intuit that the ApplicationContext defines when the Application should exit. In fact the point of all the overloads to Application.Run is to help the Application know when to quit.

Running an application without showing a form

There are really two options here:

Instead of calling Application.Run with an argument, call Application.Run() to start processing messages with NO arguments, then Application.Exit() when finished. This is not very elegant as a missed call to Application.Exit means your application will keep running even though there is no UI present.

A much cleaner solution is to inherit from the application context class and redefine when you think the application should quit. The second solution is covered in depth with sample here.