Skip to content

Instantly share code, notes, and snippets.

@JerryNixon
Created October 22, 2018 16:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JerryNixon/21c5785e3c1f8d6e4a7add40936ae805 to your computer and use it in GitHub Desktop.
Save JerryNixon/21c5785e3c1f8d6e4a7add40936ae805 to your computer and use it in GitHub Desktop.
Preventing UWP Suspension
sealed partial class App : Application
{
public App()
{
InitializeComponent();
Suspending += (s, e) => Helpers.ShowToast("Suspending");
Resuming += (s, e) => Helpers.ShowToast("Resuming");
Helpers.SetupExSession(
allowed: () => Helpers.ShowToast("Allowed"),
denied: () => Helpers.ShowToast("Denied"),
revoked: () => Helpers.ShowToast("Revoked"));
}
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
if (!(Window.Current.Content is Frame frame))
{
Window.Current.Content = frame = new Frame();
}
if (e.PrelaunchActivated == false)
{
if (frame.Content == null)
{
frame.Navigate(typeof(MainPage), e.Arguments);
}
Helpers.ShowToast("Launched");
Window.Current.Activate();
}
}
}
public static class Helpers
{
public static void ShowToast(string text)
{
var content = new ToastContent
{
Visual = new ToastVisual
{
BindingGeneric = new ToastBindingGeneric
{
Children =
{
new AdaptiveText { Text = text }
}
}
}
};
var toast = new ToastNotification(content.GetXml());
ToastNotificationManager.CreateToastNotifier().Show(toast);
}
public static async void SetupExSession(Action allowed, Action denied, Action revoked)
{
var session = new ExtendedExecutionSession
{
Reason = ExtendedExecutionReason.Unspecified
};
session.Revoked += (s, e) => revoked?.Invoke();
var result = await session.RequestExtensionAsync();
switch (result)
{
case ExtendedExecutionResult.Allowed:
allowed?.Invoke();
break;
default:
case ExtendedExecutionResult.Denied:
denied?.Invoke();
break;
}
}
}
@JerryNixon
Copy link
Author

You should be able to replace the app.xaml.cs of any new blank UWP project and test this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment