UWP:检测应用获得/失去焦点 [英] UWP: Detect app gaining/losing focus

查看:90
本文介绍了UWP:检测应用获得/失去焦点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够通过使用DisplayRequest类来防止在使用我的应用程序时触发屏幕保护程序,但是我只想在它是活动应用程序时执行此操作.如果用户切换到另一个窗口/应用程序,那么我想表现得像个好公民,并再次允许屏幕保护程序.

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. If the user switches to another window/app then I want to act like a good citizen and allow the screensaver again.

我看不到一种明显的方法来检测UWP应用何时获得/失去焦点(或被激活/停用),并且快速搜索并不能提供任何见解.谁能指出我正确的方向?

I can't see an obvious way to detect when a UWP app gets/loses focus (or is activated/deactivated) and a quick search around doesn't offer any insights. Can anyone point me in the right direction?

推荐答案

您不应处理应用程序激活状态的更改.

You should not handle the changes of app's activation state.

请参考如何防止UWP应用中的屏幕锁定.

自动处理请求

但是,如果没有任何其他编码,则当您的应用不再具有焦点时,换句话说,当您的应用进入暂停状态时,您的RequestActive()调用也将被停用.在Windows Phone移动版和Windows 10 PC或Tablet模式下的Surface Pro上,您的应用程序不再具有焦点"意味着您的应用程序不再位于前台(顺便说一句,快照的应用程序仍算在前台).但是,在桌面模式下的Windows 10 PC上,这意味着只要您的应用程序最小化即可.在桌面模式下,请注意,即使另一个应用程序窗口覆盖了您的应用程序窗口,UWP应用程序生命周期仍认为您的应用程序在前台运行.

Without any additional coding, though, your RequestActive() call will also be deactivated when your app no longer has the focus—in other words, when your app goes into a suspended state. On Windows Phone mobile and on a Windows 10 PC or Surface Pro in Tablet mode, "your app no longer having focus" means whenever your app is no longer in the foreground (snapped apps still count as being in the foreground, by the way). On a Windows 10 PC in desktop mode, however, it will mean whenever your app is minimized. In desktop mode, note that even when another app window covers up your app window, your app is still considered by the UWP app lifecycle to be running in the foreground.

真正很酷的事情是,当您的应用回到前台或最小化时,对RequestActive()的调用将自动重新激活.您不必做任何事情!

The really cool thing is that when your app comes back into the foreground or gets de-minimized, the RequestActive() call will automatically get reactivated. You don’t have to do a thing!

这还意味着,如果另一个应用程序碰巧发出了保持显示处于活动状态的请求,则它无法劫持同一设备上每个其他应用程序的行为.该请求只有在用户使用该应用程序的情况下才有效.一旦该应用被关闭或最小化,即使该应用忘记调用RequestRelease(),Windows 10也会恢复其常规的节电习惯.

This also means that if another app happens to make a request to keep the display active, it cannot hijack the behavior of every other app on the same device. The request is only good as long as the user is working with that app. Once the app is dismissed or minimized, Windows 10 goes back to its regular power conservation habits, even if the app forgets to call RequestRelease().

最后,当您的应用终止时,将自动为您清除所有剩余的显示活动请求.

Finally, when your app is terminated, all remaining display active requests are automatically cleaned up for you.

这一切都是为了满足您的需求.

It's all made for your needs.

这篇关于UWP:检测应用获得/失去焦点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆