Window.Closing Event

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Occurs when the window is about to close.

Namespace:  System.Windows
Assembly:  System.Windows (in System.Windows.dll)

Syntax

'Declaration
Public Event Closing As EventHandler(Of ClosingEventArgs)
public event EventHandler<ClosingEventArgs> Closing

Exceptions

Exception Condition
NotSupportedException

When adding or removing an event handler, the application is not running outside the browser.

Remarks

You can handle this event in order to prevent the window from closing. This is useful to perform actions such as displaying a warning if the user has unsaved changes in the application data. To cancel the event, set the Cancel property of the ClosingEventArgs object to true.

This event occurs when you call the Close method or when the user closes the window. It also occurs when the window closes for some other reason, such as system shutdown or user logoff. In these cases, however, you cannot cancel the event. To determine whether cancelation is possible, check the ClosingEventArgs.IsCancelable property.

Examples

The following code example demonstrates the use of this event. In this example, the current window position and dimensions are saved to the ApplicationSettings in the isolated storage as a user defined key/value pair. These values can be retrieved at application startup to set the window settings.

' Event handler for the Window.Closing event.
Private Sub MainWindow_Closing(ByVal sender As System.Object, ByVal e As System.ComponentModel.ClosingEventArgs)
    If Application.Current.IsRunningOutOfBrowser Then
        ' Show a message when application shuts down and
        ' give the user a chance to cancel the operation.
        If (MessageBox.Show(
            "Are you sure you want to close this application.",
            "Application Shutdown",
            MessageBoxButton.OKCancel) = MessageBoxResult.OK) Then

            ' Get the main window.
            Dim mainWindow As Window = Application.Current.MainWindow

            ' Call helper method to save the window settings.
            SetApplicationSetting("WindowTop", mainWindow.Top.ToString)
            SetApplicationSetting("WindowLeft", mainWindow.Left.ToString)
            SetApplicationSetting("WindowWidth", mainWindow.Width.ToString)
            SetApplicationSetting("WindowHeight", mainWindow.Height.ToString)
        Else
            ' Cancel the appliation shutdown.
            e.Cancel = True
        End If
    End If
End Sub

' Helper function to set an application setting.
Private Sub SetApplicationSetting(ByVal key As String, ByVal value As String)

    ' Get the Application Settings.
    Dim appSettings As IsolatedStorageSettings = IsolatedStorageSettings.ApplicationSettings

    ' Save the window settings to IsolatedStorage.
    Try
        If Not appSettings.Contains(key) Then
            IsolatedStorageSettings.ApplicationSettings.Add(key, value)
        Else
            appSettings(key) = value
        End If
    Catch ex As Exception
        ' Logic to handle exception. 
    End Try
End Sub
// Event handler for the Window.Closing event.
void MainWindow_Closing(object sender, System.ComponentModel.ClosingEventArgs e)
{
    if (Application.Current.IsRunningOutOfBrowser)
    {
        // Show a message when application shuts down and
        // and give the user a chance to cancel the operation.
        if (MessageBox.Show(
                "Are you sure you want to close this application.",
                "Application Shutdown",
                MessageBoxButton.OKCancel) == MessageBoxResult.OK)
        {
            // Get the main window.
            Window mainWindow = Application.Current.MainWindow;

            // Call helper method to save the window settings.
            SetApplicationSetting("WindowTop", mainWindow.Top.ToString());
            SetApplicationSetting("WindowLeft", mainWindow.Left.ToString());
            SetApplicationSetting("WindowWidth", mainWindow.Width.ToString());
            SetApplicationSetting("WindowHeight", mainWindow.Height.ToString());
        }
        else
        {
            // Cancel the appliation shutdown.
            e.Cancel = true;
        }
    }
}

// Helper function to set an application setting.
private void SetApplicationSetting(string key, string value)
{
    // Get the Application Settings.
    IsolatedStorageSettings appSettings = IsolatedStorageSettings.ApplicationSettings;

    // Save the window settings to IsolatedStorage.
    try
    {
        if (!appSettings.Contains(key))
        {
            IsolatedStorageSettings.ApplicationSettings.Add(key, value);
        }
        else
        {
            appSettings[key] = value;
        }
    }
    catch (KeyNotFoundException)
    {
        // Logic to handle exception. 
    }
}

By default, you cannot reuse a window after it is closed. To display and hide a window multiple times, you must set its Visibility property and cancel its Closing event, as shown in the following code example. This example requires a UserControl subclass named DemoUserControl. Additionally, this example will work only in a trusted, out-of-browser application targeting Silverlight 5.

Private Sub ShowHideDemoWindowButton_Click(
    sender As System.Object, e As System.Windows.RoutedEventArgs)

    If (Not Application.Current.IsRunningOutOfBrowser OrElse _ 
        Not Application.Current.HasElevatedPermissions) Then Return

    DemoWindow.Visibility = If(DemoWindow.IsVisible,
        Visibility.Collapsed, Visibility.Visible)

End Sub

Private _demoWindow As Window
Private ReadOnly Property DemoWindow As Window
    Get
        If (Not Application.Current.IsRunningOutOfBrowser OrElse
            Not Application.Current.HasElevatedPermissions) Then Return Nothing

        If _demoWindow Is Nothing Then
            _demoWindow = New Window With
            {
                .Title = "Demo Window",
                .Content = New DemoUserControl(),
                .Height = 300, .Width = 300, .Top = 0, .Left = 0
            }

            AddHandler _demoWindow.Closing,
                Sub(sender As Object,
                    e As System.ComponentModel.ClosingEventArgs)
                    If (e.IsCancelable) Then
                        e.Cancel = True
                        _demoWindow.Visibility = Visibility.Collapsed
                    End If
                End Sub
        End If

        Return _demoWindow
    End Get
End Property
private void ShowHideDemoWindowButton_Click(object sender, RoutedEventArgs e)
{
    if (!Application.Current.IsRunningOutOfBrowser || 
        !Application.Current.HasElevatedPermissions) return;
    DemoWindow.Visibility = DemoWindow.IsVisible ?
        Visibility.Collapsed : Visibility.Visible;
}

private Window _demoWindow;
private Window DemoWindow
{
    get
    {
        if (!Application.Current.IsRunningOutOfBrowser || 
            !Application.Current.HasElevatedPermissions) return null;

        if (_demoWindow == null)
        {
            _demoWindow = new Window()
            {
                Title = "Demo Window",
                Content = new DemoUserControl(),
                Height = 300, Width = 300, Top = 0, Left = 0
            };

            _demoWindow.Closing += (sender, e) =>
            {
                if (e.IsCancelable)
                {
                    e.Cancel = true;
                    _demoWindow.Visibility = Visibility.Collapsed;
                }
            };
        }

        return _demoWindow;
    }
}

Version Information

Silverlight

Supported in: 5, 4

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.