Geeks With Blogs


Timmy Kokke's Blog

↑ Grab this Headline Animator

Timmy Kokke at Blogged
Timmy Kokke …just sorting my bubbles…


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 ( 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()
    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?",
        MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
            e.Cancel = true;


One last note: you might want to add a check if the application is running out-of-browser. Using the closing event in browser causes an exception.


Technorati Tags: ,
Posted on Wednesday, July 7, 2010 7:37 PM Silverlight , dotnetmag | Back to top

Comments on this post: Window Closing Event

No comments posted yet.
Your comment:
 (will show your gravatar)

Copyright © Timmy Kokke | Powered by: