Silverlight

Window Closing Event

Intro

When running Silverlight 4 out of the browser it could become handy to know that the application is being closed. In case of my open source demo application SilverAmp (http://SilverAmp.CodePlex.com) I wanted to notify the user the application is being closed when music is still playing.

Catching the event

In Silverlight 4 a new event has been added to the System.Window class. This event is raised when the application is being closed. Closed in any way: by the user hitting F4; by the user clicking on the right-top cross; by a calling close on the application from within code or even when windows is shut down.

The great thing about handling this event is that you can cancel it. In the example below the closing event is handled and the user is asked if he wants to exit the application. The application uses a MediaPlayer to play media which is named _internalPlayer. If the currentState of the player is playing than a message box is shown. If the user chooses not to quit, the closing is canceled by setting the Cancel property of the ClosingEventArgs to true.

public MainPage()
{
    InitializeComponent();
    Application.Current.MainWindow.Closing +=
                         MainWindow_Closing;
}
void MainWindow_Closing(object sender, 
                  System.ComponentModel.ClosingEventArgs e)
{
    if (_internalPlayer.CurrentState 
                        == MediaElementState.Playing)
    {
        if (MessageBox.Show(
                "Music is playing, exit application?",
                "Exit",
                MessageBoxButton.OKCancel) == 
                        MessageBoxResult.Cancel)
        {
            e.Cancel = true;
        }
    }
}

Leave a Reply

Seo wordpress plugin by www.seowizard.org.
%d bloggers like this: