This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Windows Presentation Foundation
.NET 4.0+

WPF Controls - Window - Display and Activation

The one hundred and sixty-ninth part of the Windows Presentation Foundation Fundamentals tutorial continues to describe the Window class. This article looks at the members related to opening, closing, activating and deactivating windows.

Activating a Window

When you have an application with multiple windows, only one can be active at any time. This is the window that will receive keyboard input. The active window is usually shown with a differently coloured title bar.

The user can activate a window by clicking it. You can also activate a window programmatically by calling its Activate method. If you need to check if a window is active, you can read the Boolean IsActive property.

Let's update the program so that clicking the "Activate Main" button in any secondary window activates the main window. Start by updating the XAML for the button to register the Click event:

<Button Click="ActivateMain_Click">Activate Main</Button>

You can identify the main window of an application by reading the MainWindow property from the Application object. For the running application, you can obtain this using the Application.Current.MainWindow static property. Once you have a reference to the window, you can call its Activate method.

Add the following code behind the secondary window to respond to the button being clicked. Note that the MainWindow property is first checked to see if it is null. This will be the case if the main window has been closed.

private void ActivateMain_Click(object sender, RoutedEventArgs e)
    if (Application.Current.MainWindow != null)

Run the program, open a secondary window and click the "Activate Main" button. The main window will become active.

Detecting Activation

You can detect a window become active or deactivating, whether this is due to the Active method being called or a user action. To do so, capture the Activated and Deactivated events for the window.

Let's register both events in the SecondWindow XAML. Update the opening tag of the Window element, as follows:

<Window x:Class="WindowDisplayDemo.SecondWindow"
        Title="Window Demo" Height="150" Width="250"
        Activated="Window_Activated" Deactivated="Window_Deactivated">

We'll update the Title property of the window in response to each event. The new title will show the current status of the window. Add the following code behind the window.

private void Window_Activated(object sender, EventArgs e)
    Title = "Active Window";

private void Window_Deactivated(object sender, EventArgs e)
    Title = "Inactive Window";

Run the program and open several secondary windows to test the code. Switching between windows should update the title bars accordingly.

30 June 2015