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:

[1] .NET remoting is a technology that allows objects to talk to each other across application and machine boundaries. Remoting is beyond the scope of this book but is covered very nicely in Ingo Rammer's book Advanced .NET Remoting (APress, 2002).

// 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 eventsIdle, ThreadExit, and ApplicationExitare 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]

[2] A developer's machine is likely to have VS05 installed, and VS05 provides a much more detailed, developer-oriented dialog.

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. 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 exceptionfor example, if a file couldn't be opened or there was a security violationthe 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. 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:

[3] Application and user settings are another mechanism for doing so, and they are covered in Chapter 15: Settings.

// 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]

[4] If you want to see more robust command line parsing support, see the Genghis class library, which is available at http://www.genghisgroup.com (http://tinysells.com/8).

// 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.




Windows Forms 2.0 Programming
Windows Forms 2.0 Programming (Microsoft .NET Development Series)
ISBN: 0321267966
EAN: 2147483647
Year: 2006
Pages: 216

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net