UWP: Detect app gaining/losing focus

前端 未结 4 994
忘了有多久
忘了有多久 2020-12-16 20:20

I want to be able to prevent the screen saver from triggering while my app is in use by using the DisplayRequest class, but I only want to do this while it\'s the active app

4条回答
  •  暖寄归人
    2020-12-16 20:50

    We can use CoreWindow.Activated event to detect when a UWP app is activated or deactivated. This method is fired when the window completes activation or deactivation. And for a UWP app, we usually only have one window. So we can add some code like following in Application.OnLaunched method to detect:

    Window.Current.CoreWindow.Activated += (sender, args) =>
    {
        if (args.WindowActivationState == Windows.UI.Core.CoreWindowActivationState.Deactivated)
        {
            System.Diagnostics.Debug.WriteLine("Deactivated " + DateTime.Now);
        }
        else
        {
            System.Diagnostics.Debug.WriteLine("Activated " + DateTime.Now);
        }
    };
    

    Besides this, you can also use CoreApplication.GetCurrentView method or CoreWindow.GetForCurrentThread method to get the CoreWindow.

提交回复
热议问题