Home > Articles > Operating Systems, Server > Microsoft Windows Desktop

Application Architecture in Windows Forms 2.0

  • Print
  • + Share This
Applications have special support in Windows Forms. This chapter focuses on this topics in depth, and starts by defining what an application actually is.
This chapter is from the book

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 chapter 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:

namespace System.Windows.Forms {
 sealed class Application {

  // Properties
  public static bool AllowQuit { get; }
  public static string CommonAppDataPath { get; }
  public static RegistryKey CommonAppDataRegistry { get; }
  public static string CompanyName { get; }
  public static CultureInfo CurrentCulture { get; set; }
  public static InputLanguage CurrentInputLanguage { get; set; }
  public static string ExecutablePath { get; }
  public static string LocalUserAppDataPath { get; }
  public static bool MessageLoop { get; }
  public static FormCollection OpenForms { get; } // New
  public static string ProductName { get; }
  public static string ProductVersion { get; }
  public static bool RenderWithVisualStyles { get; } // New
  public static string SafeTopLevelCaptionFormat { get; set; }
  public static string StartupPath { get; }
  public static string UserAppDataPath { get; }
  public static RegistryKey UserAppDataRegistry { get; }
  public static bool UseWaitCursor { get; set; } // New
  public static VisualStyleState VisualStyleState { get; set; } // New
  
  // Methods
  public static void AddMessageFilter(IMessageFilter value);
  public static void DoEvents();
  public static void EnableVisualStyles();
  public static void Exit();
  public static void Exit(CancelEventArgs e); // New
  public static void ExitThread();
  public static bool FilterMessage(ref Message message); // New
  public static ApartmentState OleRequired();
  public static void OnThreadException(Exception t);
  public static void RaiseIdle(EventArgs e); // New
  public static void RegisterMessageLoop(
   MessageLoopCallback callback); // New
  public static void RemoveMessageFilter(IMessageFilter value);
  public static void Restart(); // New
  public static void Run();
  public static void Run(ApplicationContext context);
  public static void Run(Form mainForm);
  public static void SetCompatibleTextRenderingDefault(
   bool defaultValue); // New
  public static bool SetSuspendState(
   PowerState state, bool force, bool disableWakeEvent); // New
  public static void SetUnhandledExceptionMode(
   UnhandledExceptionMode mode); // New
  public static void SetUnhandledExceptionMode(
   UnhandledExceptionMode mode, bool threadScope); // New
  public static void UnregisterMessageLoop();// New

  // Events
  public static event EventHandler ApplicationExit;
  public static event EventHandler EnterThreadModal; // New
  public static event EventHandler Idle;
  public static event EventHandler LeaveThreadModal; // New
  public static event ThreadExceptionEventHandler ThreadException;
  public static event EventHandler ThreadExit;
 }
}

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:

// Program.cs
static class Program { 

 [STAThread]
 static void Main() {
  ...
  // Create and show the main form modelessly
  MainForm form = new MainForm();
  form.Show();

  // Run the application
  Application.Run();
 }
}

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:

// MainForm.cs
partial class MainForm : Form {
 ...
 void MainForm_FormClosed(object sender, FormClosedEventArgs e) {
  // Close the application when the main form goes away
  // Only for use when Application.Run is called without
  // any arguments
  Application.Exit();
 }
 ...
}

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:

// Program.cs
static class Program { 

 [STAThread]
 static void Main() {
  ...
  // Create the main form
  MainForm form = new MainForm();

  // Run the application until the main form is closed
  Application.Run(form);
 }
}

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.

Application Context

Internally, the Run method creates an instance of the ApplicationContext class. ApplicationContext detects main form closure and exits the application as appropriate:

namespace System.Windows.Forms {
 class ApplicationContext {

  // Constructors
  public ApplicationContext();
  public ApplicationContext(Form mainForm);

  // Properties
  public Form MainForm { get; set; }
  public object Tag { get; set; } // New

  // Events
  public event EventHandler ThreadExit;

  // Methods
  public void ExitThread();
  protected virtual void ExitThreadCore();
  protected virtual void OnMainFormClosed(object sender, EventArgs e);
 }
}

In fact, the Run method allows you to pass an ApplicationContext yourself:

// Program.cs
static class Program { 

 [STAThread]
 static void Main() {
  ...
  // Run the application with a context
  ApplicationContext ctx = new ApplicationContext(new MainForm());
  Application.Run(ctx);
 }
}

This is useful if you’d like to derive from the ApplicationContext class and provide your own custom context:

// TimedApplicationContext.cs
class TimedApplicationContext : ApplicationContext {

 Timer timer = new Timer();

 public TimedApplicationContext(Form mainForm) : base(mainForm) {
  timer.Tick += timer_Tick;
  timer.Interval = 5000; // 5 seconds
  timer.Enabled = true;
 }

 void timer_Tick(object sender, EventArgs e) {
  timer.Enabled = false;
  timer.Dispose();

  DialogResult res = 
   MessageBox.Show(
    "OK to charge your credit card?",
    "Time’s Up!", 
    MessageBoxButtons.YesNo);

  if( res == DialogResult.No ) {
   // See ya...
   this.MainForm.Close();
  }
 }
}

// Program.cs
static class Program { 

 [STAThread]
 static void Main() {
  ...
  // Run the application with a custom context
  TimedApplicationContext ctx = 
   new TimedApplicationContext(new MainForm());
  Application.Run(ctx);
 }
}

This custom context class waits for five seconds after an application has started and then asks to charge the user’s credit card. If the answer is no, the main form of the application is closed (available from the MainForm property of the base ApplicationContext class), causing the application to exit.

You might also encounter situations when you’d like to stop the application from exiting when the main form goes away, such as an application that’s serving .NET remoting clients and needs to stick around even if the user has closed the main form.1 In these situations, you override the OnMainFormClosed method from the ApplicationContext base class:

// RemotingServerApplicationContext.cs
class RemotingServerApplicationContext : ApplicationContext {

 public RemotingServerApplicationContext(Form mainForm) :
  base(mainForm) {}

 protected override void OnMainFormClosed(object sender, EventArgs e) {
  // Don’t let base class exit application
  if( this.IsServicingRemotingClient() ) return;

  // Let base class exit application
  base.OnMainFormClosed(sender, e);
 }

 protected bool IsServicingRemotingClient() {...}
}

When all the .NET remoting clients have exited, you must make sure that Application.Exit is called, in this case by calling the base ApplicationContext class’s OnMainFormClosed method.

Application Events

During the lifetime of an application, several key application events—Idle, ThreadExit, and ApplicationExit—are fired by the Application object. You can subscribe to application events at any time, but it’s most common to do it in the Main function:

// Program.cs
static class Program {

 [STAThread]
 static void Main() {
  ...
  Application.Idle += App_Idle;
  Application.ThreadExit += App_ThreadExit;
  Application.ApplicationExit += App_ApplicationExit;

  // Run the application
  Application.Run(new MainForm());
 }
 
 static void App_Idle(object sender, EventArgs e) {...}
 static void App_ThreadExit(object sender, EventArgs e) {...}
 static void App_ApplicationExit(object sender, EventArgs e) {...}
}

The Idle event happens when a series of events have been dispatched to event handlers and no more events are waiting to be processed. The Idle event can sometimes be used to perform concurrent processing in tiny chunks, but it’s much more convenient and robust to use worker threads for those kinds of activities. This technique is covered in Chapter 18: Multithreaded User Interfaces.

When a UI thread is about to exit, it receives a notification via the ThreadExit event. When the last UI thread goes away, the application’s ApplicationExit event is fired.

UI Thread Exceptions

One other application-level event that is fired as necessary by the Application object is the ThreadException event. This event is fired when a UI thread causes an exception to be thrown. This one is so important that Windows Forms provides a default handler if you don’t.

The typical .NET unhandled-exception behavior on a user’s machine yields a dialog, as shown in Figure 14.1.2

Figure 14.1

Figure 14.1 Default .NET Unhandled-Exception Dialog

This kind of exception handling tends to make users unhappy. This dialog isn’t necessarily explicit about what actually happened, even if you view the data in the error report. And worse, there is no way to continue the application to attempt to save the data being worked on at the moment. On the other hand, a Windows Forms application that experiences an unhandled exception during the processing of an event shows a more specialized default dialog like the one in Figure 14.2.

Figure 14.2

Figure 14.2 Default Windows Forms Unhandled-Exception Dialog

This dialog is the ThreadExceptionDialog (from the System.Windows.Forms namespace), and it looks functionally the same as the one in Figure 14.1, with one important difference: The Windows Forms version has a Continue button. What’s happening is that Windows Forms itself catches exceptions thrown by event handlers; in this way, even if that event handler caused an exception—for example, if a file couldn’t be opened or there was a security violation—the user is allowed to continue running the application with the hope that saving will work, even if nothing else does. This safety net makes Windows Forms applications more robust in the face of even unhandled exceptions than Windows applications of old.

However, if an unhandled exception is caught, the application could be in an inconsistent state, so it’s best to encourage your users to save their files and restart the application. To implement this, you replace the Windows Forms unhandled-exception dialog with an application-specific dialog by handling the application’s thread exception event:

// Program.cs
static class Program {

 [STAThread]
 static void Main() {
  // Handle unhandled thread exceptions
  Application.ThreadException += App_ThreadException;
  ...
  // Run the application
  Application.Run(new MainForm());
 }

 static void App_ThreadException(
  object sender, ThreadExceptionEventArgs e) {
  // Does user want to save or quit?
  string msg = 
   "A problem has occurred in this application:\r\n\r\n" +
   "\t" + e.Exception.Message + "\r\n\r\n" +
   "Would you like to continue the application so that\r\n" +
   "you can save your work?";
  DialogResult res = MessageBox.Show(
   msg, 
   "Unexpected Error", 
   MessageBoxButtons.YesNo);
   ...
 }
}

Notice that the thread exception handler takes a ThreadExceptionEventArgs object, which includes the exception that was thrown. This is handy if you want to tell the user what happened, as shown in Figure 14.3.

Figure 14.3

Figure 14.3 Custom Unhandled-Exception Dialog

If the user wants to return to the application to save work, all you need to do is return from the ThreadException event handler. If, on the other hand, the user decides not to continue with the application, calling Application.Exit shuts down the application. Both are shown here:

// Program.cs
static class Program {
 ...
 static void App_ThreadException(
  object sender, ThreadExceptionEventArgs e) {
  ...
  // Save or quit
  DialogResult res = MessageBox.Show(...);

  // If save: returning to continue the application and allow saving
  if( res == DialogResult.Yes ) return;

  // If quit: shut ’er down, Clancy, she’s a’pumpin’ mud!
  Application.Exit();
}

Handling exceptions in this way gives users a way to make decisions about how an application will shut down, if at all, in the event of an exception. However, if it doesn’t make sense for users to be involved in unhandled exceptions, you can make sure that the ThreadException event is never fired. Call Application.SetUnhandledExceptionMode:

Application.SetUnhandledExceptionMode(
 UnhandledExceptionMode.ThrowException);

Although it’s not obvious from the enumeration value’s name, this code actually prevents ThreadException from being fired. Instead, it dumps the user straight out of the application before displaying the .NET unhandled-exception dialog from Figure 14.1:

namespace System.Windows.Forms {
 enum UnhandledExceptionMode {
  Automatic = 0, // default
  ThrowException = 1, // Never fire Application.ThreadException
  CatchException = 2, // Always fire Application.ThreadException
 }
}

In general, the behavior exhibited by UnhandledExceptionMode.ThrowException isn’t the most user friendly, or informative, when something catastrophic happens. Instead, it’s much better to involve users in deciding how an application shuts down.

Going the other way, you can also use command line arguments to let users make decisions about how they want their application to start up.

Passing Command Line Arguments

Command line arguments allow users to determine an application’s initial state and operational behavior when launched.3 Before command line arguments can be processed to express a user’s wishes, they need to be accessed. To do this, you change your application’s entry point method, Main, to accept a string array to contain all the passed arguments:

// Program.cs
static class Program {
 [STAThread]
 static void Main(string[] args) {
  ...
 }
}

.NET constructs the string array by parsing the command line string, which means extracting substrings, delimited by spaces, and placing each substring into an element of the array. Command line syntax, which dictates which command line arguments your application can process and the format they should be entered in, is left up to you. Here is one simple approach:

// Program.cs
static class Program {
 [STAThread]
 static void Main(string[] args) {
  ...
  bool flag = false;
  string name = "";
  int number = 0;

  // *Very* simple command line parsing
  for( int i = 0; i != args.Length; ++i ) {
   switch( args[i] ) {
    case "/flag": flag = true; break;
    case "/name": name = args[++i]; break;
    case "/number": number = int.Parse(args[++i]); break;
    default: MessageBox.Show("Invalid args!"); return;
   }
  }
  ...
 }
}

If your static Main method isn’t where you want to handle the command line arguments for your application session, GetCommandLineArgs can come in handy for retrieving the command line arguments for the current application session:4

// Program.cs
static class Program {
 [STAThread]
 static void Main() {
  ...
  string[] args = Environment.GetCommandLineArgs();

  // *Very* simple command line parsing
  // Note: Starting at item [1] because args item [0] is exe path
  for( int i = 1; i != args.Length; ++i ) {
   ...
  }
  ...
 }
}

You can see that GetCommandLineArgs always returns a string array with at least one item: the executable path.

Processing command line arguments is relatively straightforward, although special types of applications, known as single-instance applications, need to process command line arguments in special ways.

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020