This is a mirror of official site: http://jasper-net.blogspot.com/

How to cancel the closing of your Silverlight application (in-browser and out-of-browser)

| Monday, January 31, 2011
It’s almost two years ago when I wrote about the concept of canceling the the closing of a Silverlight application. In that era I was only trying to solve the problems that exist inside the browser. Like someone who accidently closes the tab, or types a new url in the tab of the Silverlight application. These things aren’t always a problem, but in Line of Business applications you would at least want to warn the user when he has unsaved data on the screen he’s about to close.

Nowadays we have Silverlight applications that run both in the browser and out-of-browser on the desktop. Of course some features can be different between the two versions of the application. But my intend is to have at least a feeling that 100% of the features are equal.

So I want to give my users a warning when they are exiting the application, either in-browser or out-of-browser. Even more, I want the warning to be much similar.
I want a simple message to be shown automatically. So let’s implement the ICloseHandler

public interface ICloseHandler
{
   string Message { get; set; }
   void Initialize();
}

Out of Browser
Although it might sound like a difficult task, it isn’t. Implementing a warning on exiting an out of browser app is as simple as listening to the Closing event of the MainWindow. In that occasion we simply show a messagebox and depending on the result we cancel the closing. The implementation of the ICloseHandler looks like this.

public class OutOfBrowserCloseHandler : ICloseHandler
{
   #region ICloseHandler Members

   public void Initialize()
   {
       Application.Current.MainWindow.Closing +=
           (s, e) =>
               {
                   MessageBoxResult boxResult = MessageBox.Show(
                       string.Format(
                           @"Are you sure you want to close the application?{1}{1}{0}",
                           Message, Environment.NewLine),
                       string.Empty,
                       MessageBoxButton.OKCancel);
                   if (boxResult == MessageBoxResult.Cancel)
                       e.Cancel = true;
               };
   }

   public string Message { get; set; }

   

Posted via email from Jasper-net

0 comments: