WPF Application creation, an insight — part2
Before I can start with part2, a small highlights from part1.
- All the WPF applications are an object of System.Windows.Application running as a process
- Visual Studio allows the users to relax from the creation and running of the System.Windows.Application object if you specify the BuildAction as Application Definition
- Specifying the StartupUri attribute in the App.xaml with a window class allows the developer not to write snippets that will show the top level window
Accessing Application object from window classes
As soon as the Application object is created, it would be set to the Current property of itself. As this property is a static property, any window classes can access the instance of app that is running. Also the application object, as mentioned earlier, shall hold the instances of all the top level windows. So we can even access these top level window object from any class thru’ the Current.Windows property.
class Window1
{
public Window1() //constructor
{
foreach(Window aTopLevelWindow in App.Current.Windows as Window)
{
MessageBox.Show(aTopLevelWindow.Title);
}
}
}
Shutting down the Application object
While running an Application object is done thru’ Run(), we can shut down the app thru’ Shutdown(). For example, if you want to provider a custom close button in your window, you can close the application (terminate the entire process) using the following snippet,
class Window1
{
...
public void ExplicitShutDown() //Some method which will explicity shutdown the Application object
{
App.Current.Shutdown(); //Where App is the name of the Application class
}
}
This is called as an explicit shutdown.
Application Events
Here are some of the events of the Application object that can be of great use when you program.
- Startup — Invoked after the Application object is created and run. You can show your top level windows in here
- Activated and Deactivated — Invoked when one of the top level windows of the Application object is activated and deactivated will be called when another Application object’s top level window gets activated
- Session Ending — Invoked when windows session ends either by a shutdown call or a restart call
- Exit — Invoked when the Application.Shutdown() is called
Hope these two posts helped you in understanding how a WPF application gets instantiated. From my next post I will start writing about controls.


[...] in the snippet. Here we override the Startup event of the Application class (refer to my previous post on Application Events) so that we can validate the mutex during the start of the [...]
Creating a single instance application in C#, WPF at Codelog
30 May 09 at 10:36 am