#610 – Application Event Sequence

The sequence of events for an application’s main Application object that are fired are as follows (all events listed in the order that they fire):

When you start the application:

  • Startup
  • Activated

When you shut the application down normally (i.e. close main window):

  • Deactivated
  • Exit

If the application experiences an unhandled exception:

  • DispatcherUnhandledException

If user is logging out of or shutting down Windows:

  • Deactivated
  • SessionEnding

Application gets focus:

  • Activated

Application loses focus:

  • Deactivated

#199 – An Application’s Windows Property Lists All of Its Windows

The Application class has a Windows property which is a collection of all of the windows that have been created by the current application.

Assume that we have an application with a main window that includes the following two buttons:

Whenever the user clicks on the Create New Window button, we create and show a new window.

    private void btnCreate_Click(object sender, System.Windows.RoutedEventArgs e)
    {
        AnotherWindow win = new AnotherWindow();
        win.Title = DateTime.Now.ToLongTimeString();
        win.Show();
    }

In the Click event handler for the Where Are the Windows? button, we can iterate through all of the windows that the application created and display some information about each one.

        private void btnWhere_Click(object sender, RoutedEventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            foreach (Window w in App.Current.Windows)
            {
                sb.AppendFormat("Window [{0}] is at ({1},{2}).\n", w.Title, w.Top, w.Left);
            }

            MessageBox.Show(sb.ToString(), "My Windows");
        }

The final result:

#197 – Override Application Class Methods for Standard Events

We’ve already mentioned some of the main events that the Application class fires–e.g. Startup, Exit and SessionEnding.  We also showed how you can add event handlers to your Application-derived class to handle these events, using SessionEnding as our example.

Rather than adding an event handler for Application.SessionEnding to our class, we could have just overridden the OnSessionEnding method.  This is more appropriate in a class that already derives from Application.  Instead of specifying the handler in App.xaml and adding the handler to App.xaml.cs, we can just add code for the override to App.xaml.cs.

As an example, the override for OnSessionEnding could look something like this:

	public partial class App : Application
	{
            protected override void OnSessionEnding(SessionEndingCancelEventArgs e)
            {
                // Always call method in base class, so that the event gets raised.
                base.OnSessionEnding(e);

                // Place your own SessionEnding logic here
            }
    }

#44 – Application is a Singleton

The System.Application class is a singleton, which means that you can create at most one instance of Application (within a single AppDomain).  If you try creating a second instance of Application, you’ll get an InvalidOperationException.

You can access the current Application object through the static property Application.Current.  (Or use property of the derived class, e.g. App.Current).

#43 – What Happens in WPF Main() Function

When creating a new WPF standalone application using the New Project wizard in Visual Studio 2010, Visual Studio automatically creates a class that derives from System.Windows.Application, as well as a static Main() function that will be the first function called when the application is started.

Here’s how the main application object is defined:

 public partial class App : Application

During the Main method, the application is started up by:

  • Creating a new instance of the Application object
  • Calling Application.InitializeComponent to constitute the application from App.xaml
  • Calling Application.Run to start the application
public static void Main()
{
    WpfApplication.App app = new WpfApplication.App();
    app.InitializeComponent();
    app.Run();
}

#40 – Application Lifetime

The diagram below shows a simplified view of the lifetime of a WPF application, as defined by the events that the Application class fires.  (The events are underlined).  Click the diagram to see a full-sized version.

The main events fired from Application include:

  • Startup - Application is starting up.
  • Exit – Fired when an application is shutting down.  Shutdown can’t be canceled.
  • Activated – Fired when an application gets focus, i.e. becomes the foreground application
  • Deactivated – Fired when application loses focus, i.e. is no longer the foreground application
  • DispatcherUnhandledException – Fired when an exception is thrown, but not yet handled.  You can choose to handle the exception or not
  • SessionEnding – Fired when Windows is being shut down–due to either logoff or Windows shutdown.  You can cancel the shutdown sequence.

You can add custom code for any of these events by just overriding the OnEventName method in your Application-derived class, e.g. OnStartup.

#38 – The Application Class

Application is a class that represents a WPF application running as a standalone client application in Windows.  Each running application contains at most a single instance of Application.

WPF applications created using the Visual Studio 2010 wizard will contain the definition of the Application object in the App.xaml file.

<Application x:Class="WpfApplication9.App"
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
     StartupUri="MainWindow.xaml">
   <Application.Resources>

   </Application.Resources>
</Application>

The Application object is responsible for:

  • Managing application lifetime (e.g. responding to startup/shutdown events)
  • Window, property and resource management
  • Command-line processing
  • Navigation
Follow

Get every new post delivered to your Inbox.

Join 240 other followers