Confirmation when closing app in UWP IL2CPP

We want the user to be able to save what they are doing before exiting the app using the close button. For other platforms, we register with Application.wantsToQuit, but on UWP this doesn’t work.

In the docs page for Application.quitting it says that in UWP “there’s no application quit event”.

There is, but it only works with XAML, not D3D, and it requires declaring an extra capability. Microsoft lets us define a “restricted” capability in the Package.appxmanifest to intercept the app closing event:

   <Capabilities>
       <rescap:Capability Name="confirmAppClose"/>
   </Capabilities>

After this, we can use this code on the App.xaml.cs file to register with the event:

   SystemNavigationManagerPreview.GetForCurrentView().CloseRequested += App_CloseRequested;

   private void App_CloseRequested(object sender, SystemNavigationCloseRequestedPreviewEventArgs e)
   {
       Debug.Log("Got here!");
   }

Instead of printing we could call something in our C# code and do whatever we need.

However, this is on .NET projects. On IL2CPP things get complicated. It’s C++, so in the App.xaml.cpp we do:

   SystemNavigationManagerPreview::GetForCurrentView()->CloseRequested += ref new EventHandler<SystemNavigationCloseRequestedPreviewEventArgs^>(this, &App::App_CloseRequested);

    void App::App_CloseRequested(Platform::Object^ object, SystemNavigationCloseRequestedPreviewEventArgs^ args)
    {
       OutputDebugString("Got here!");
   }

Problem is… what now?

  • How would this code be able to call our code that was converted from C# to C++ via IL2CPP?
  • Is there an easier way to do this?
  • Could this be implemented natively in Unity, so that Application.wantsToQuit works, with the caveat that it needs to use XAML and the extra capability?

Thanks for any help you can provide.

You don’t have add the code you posted in App.xaml.cpp. You can just do it in your scripts on Unity side:

using UnityEngine;

#if ENABLE_WINMD_SUPPORT
using Windows.UI.Core.Preview;
#endif

class ConfirmCloseBehaviour : MonoBehaviour
{
    void Awake()
    {
#if ENABLE_WINMD_SUPPORT
        UnityEngine.WSA.Application.InvokeOnUIThread(() =>
        {
            SystemNavigationManagerPreview.GetForCurrentView().CloseRequested += App_CloseRequested;
        }, false);
#endif
    }
  
#if ENABLE_WINMD_SUPPORT
   void App_CloseRequested(object sender, SystemNavigationCloseRequestedPreviewEventArgs e)
   {
       Debug.Log("Got here!");
   }
#endif
}
4 Likes

Thanks a lot @Tautvydas-Zilys ! You’re a lifesaver. :smile:

There was an easier way after all. :wink: