Window Closing Event in Silverlight 4


In this article, we will take a look at the window closing event handling capability in Silverlight 4.

Silverlight provides a feature to allow applications run out-of-browser and Silverlight 4 introduces the capability to allow catching the window close action when the application is running in the out-of-browser mode. This raises the possibility of executing further actions at the time of close. The window close action may be initiated either by the user or through a system shutdown or log off. If the user has initiated the window close (eg. By clicking on the X button on the window upper right corner), the closing of the window can also be cancelled within the application.

Let's take a look at sample code now. In the sample below, within the out-of-browser mode, the application provides a checkbox option to prevent Window close and instead initiate a Save operation and minimize the window instead of closing it. In order to allow the application to minimize the window, we need to set the application to run with Elevated.

SLWndClos_1OOBSetting.jpg

Image 1: "Out of browser" Mode 

SLWndClos_2ElevatedTrust.JPG

Image 2: Elevated Trust Setting 

First we add a checkbox named 'chkMinimizeClose' and set the display text accordingly. Next, we add code to the Load event handler to wire up the Window closing event, only when the application is being run out of browser.

private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
   if (Application.Current.IsRunningOutOfBrowser)
   {
       Window appWindow = Application.Current.MainWindow;
       appWindow.Closing += appWindow_Closing;
   }
}

Finally, we add code to handle the window closing event. In this event handler method, we will check if the close event was triggered by the user, by checking the IsCancelable property of the ClosingEventArgs parameter object. If it is a user triggered window close and the user has set the checkbox to Minimize instead of closing the window, we invoke a Save method (placeholder here) and cancel the closing.

void appWindow_Closing(object sender, System.ComponentModel.ClosingEventArgs e)
{
   if (chkMinimizeClose.IsChecked == false && e.IsCancelable)
   {
      SaveChanges();
      App.Current.MainWindow.WindowState = WindowState.Minimized;
      e.Cancel = true;
   }
}

We can also modify or extend this sample code to provide a closing message to the user, include more code to be executed at the time of window close, provide reminders/information to the user when the application is being closed and to prevent window being closed in certain conditions. Do make sure you allow the user a choice to exit the application!

Here is the complete source code: 

XAML

<UserControl x:Class="Art_WndClos.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400" Loaded="UserControl_Loaded">
    <Grid x:Name="LayoutRoot" Background="White">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="380*" />
            <ColumnDefinition Width="20*" />
        </Grid.ColumnDefinitions>
        <Button Content="Button" Height="33" HorizontalAlignment="Left" Margin="48,48,0,0" Name="button1" VerticalAlignment="Top" Width="117" />
        <CheckBox Content="Save and Minimize without closing" Height="16" HorizontalAlignment="Left" Margin="21,12,0,0" Name="chkMinimizeClose" VerticalAlignment="Top"/>
    </Grid>
</UserControl>

Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Art_WndClos
{
    public partial class MainPage : UserControl
    {
        public bool bCloseOK;
        public MainPage()
        {
            InitializeComponent();
        }
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            if (Application.Current.IsRunningOutOfBrowser)
            {
                Window appWindow = Application.Current.MainWindow;
                appWindow.Closing += appWindow_Closing;
            }
        }
        void appWindow_Closing(object sender, System.ComponentModel.ClosingEventArgs e)
        {
            if (chkMinimizeClose.IsChecked == true && e.IsCancelable)
            {
                //SaveChanges();
                App.Current.MainWindow.WindowState = WindowState.Minimized;
                e.Cancel = true;
            }
        }
   }
}

Conclusion

We have now taken a look at the new Silverlight 4 feature to respond to a manual window closing event, when the application is running in the "out of browser" mode. 

Happy Coding!


Similar Articles