I've found plenty of examples of writing code that executes when a WPF or Windows Forms app terminates, but not for a UWP app. Is there any special C# method you can override, or an event handler you can use to contain cleanup code?
Here is the WPF code I tried but did not work in my UWP app:
App.xaml.cs
(without the boilerplate usings and namespace declaration)
public partial class App : Application
{
void App_SessionEnding(object sender, SessionEndingCancelEventArgs e)
{
MessageBox.Show("Sorry, you cannot log off while this app is running");
e.Cancel = true;
}
}
App.xaml
<Application x:Class="SafeShutdownWPF.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SafeShutdownWPF"
StartupUri="MainWindow.xaml"
SessionEnding="App_SessionEnding">
<Application.Resources>
</Application.Resources>
</Application>
I tried to use Process.Exited
, but VS2015 could not recognize Process inside of System.Diagnostics
.
Run on an emulatorIn Android Studio, create an Android Virtual Device (AVD) that the emulator can use to install and run your app. In the toolbar, select your app from the run/debug configurations drop-down menu. From the target device drop-down menu, select the AVD that you want to run your app on. Click Run .
Tap Keep open for quick launching. The app will always be in memory. If you want to remove it so you can select another service, tap the Lock icon on the lower corner of the app. That will clear it from memory.
For UWP apps, you need to use the Suspending
event on the Application
object. If you used the default project template then you should already have a OnSuspending
method defined, you just have to fill it. Otherwise, subscribe to the event in the constructor:
public App()
{
this.InitializeComponent();
this.Suspending += OnSuspending;
}
And the method should look like (using a deferral to allow asynchronous programming):
private void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
//TODO: Save application state and stop any background activity
deferral.Complete();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With