Windows Forms: Applications | WebReference

Windows Forms: Applications


[next]



Applications have special support in Windows Forms. For starters, you can manage and tailor your application's lifetime, and, when the work flow is disrupted by an unhandled exception, you can choose from several methods of response. Then, there are several application models that you can employ, including Single Document Interface (SDI) and Multiple Document Interface (MDI) applications, each of which can support either multiple-instance or single-instance mode, the former the VS05 default and the latter requiring special consideration. All applications, however, can discover and use a wide variety of information about the system and environment they execute in.

This tutorial focuses on these topics in depth, and starts by defining what an application actually is.

Applications

An application is anything with an .exe extension that can be started from the Windows shell. However, applications are also provided for directly in Windows Forms by the Application class:

Notice that all the members of the Application class are static. Although there is per-application state in Windows Forms, there is no instance of an Application class. Instead, the Application class is a scoping mechanism for exposing the various services that the class provides, including control of application lifetime and support for message handling.

Application Lifetime

A Windows Forms application starts when the Main method is called. However, to initialize a Windows Forms application fully and start it routing Windows Forms events, you need to invoke Application.Run in one of three ways.

The first is simply to call Run with no arguments. This approach is useful only if other means have already been used to show an initial UI:

When you call Run with no arguments, the application runs until explicitly told to stop, even when all its forms are closed. This puts the burden on some part of the application to call the Application class Exit method, typically when the main application form is closing:

Typically, you call Application.Run without any arguments only when the application needs a secondary UI thread. A UI thread is one that calls Application.Run and can process the events that drive a Windows application. Because a vast majority of applications contain a single UI thread and because most of them have a main form that, when closed, causes the application to exit, another overload of the Run method is used far more often. This overload of Run takes as an argument a reference to the form designated as the main form. When Run is called in this way, it shows the main form and doesn't return until the main form closes:

In this case, there is no need for explicit code to exit the application. Instead, Application watches for the main form to close before exiting.


[next]