Search code examples
c#wpfeventsbrowserxbap

How to handle the Before Close Event in a WPF Browser Application?


I am just starting with a WPF Browser application.

I would like to handle the Before Close Event of the browser, so how would i handle that event?


Solution

  • I found this solution.

    In the App.xaml.cs file:

     private void Application_Onexit(object sender, ExitEventArgs e)
    
            { 
    
              //write your code in here!
    
            }
    

    In the App.xaml file:

    <Application x:Class="(yourclasss)"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 Startup="Application_Startup"
                 Exit="Application_Onexit"
                 ShutdownMode="OnLastWindowClose"
                 StartupUri="startup.xaml">
    

    So basically the ShutdownMode property needs to be set in order to make it work.

    Then add a event in app.xaml.cs:

    public static event EventHandler UnloadPageWorkaround;
    
    public void Application_Onexit(object sender, ExitEventArgs e)
    {
        UnloadPageWorkaround.Invoke(null, null);
    }
    

    Then on the relevant page:

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
    
            WPFBrowser.App.UnloadPageWorkaround += new EventHandler(DoMySpecialPageCleanupStuff);
        }
    
        void DoMySpecialPageCleanupStuff(object sender, EventArgs e)
        {
            //do cleanup
        }       
    

    The only problem with this is, you can't stop the application from exiting.

    Hope it helps.