每当用户移动到另一个应用程序时,我都会想要暂停一个游戏.例如,当选择超级按钮菜单时,用户将
Windows键,alt-tab按到另一个应用程序,单击另一个应用程序或任何其他会使应用程序失去焦点的应用程序.
当然这应该是微不足道的!我只有一个Page和一个Canvas,我在Canvas上尝试了GotFocus和LostFocus事件,但它们并没有激发.
我最接近的是在捕获指针后在CoreWindow上使用PointerCaptureLost.当选择了超级按钮菜单时,这适用于应用程序切换,但是当按下Windows键时这不起作用.
编辑:
在下面的Chris Bowen的帮助下,最终的“解决方案”如下:
- public MainPage() {
- this.InitializeComponent();
- CapturePointer();
- Window.Current.CoreWindow.PointerCaptureLost += PointerCaptureLost;
- Window.Current.CoreWindow.PointerPressed += PointerPressed;
- Window.Current.VisibilityChanged += VisibilityChanged;
- }
- private void VisibilityChanged(object sender,VisibilityChangedEventArgs e) {
- if(e.Visible) {
- CapturePointer();
- }
- else {
- Pause();
- }
- }
- void PointerPressed(CoreWindow sender,PointerEventArgs args) {
- CapturePointer();
- }
- private void CapturePointer() {
- if(hasCapture == false) {
- Window.Current.CoreWindow.SetPointerCapture();
- hasCapture = true;
- }
- }
- void PointerCaptureLost(CoreWindow sender,PointerEventArgs args) {
- hasCapture = false;
- Pause();
- }
- private bool hasCapture;
它似乎仍然应该是一种更简单的方式,所以如果你发现更优雅的东西,请告诉我.
解决方法
尝试使用
Window.VisibilityChanged活动.像这样的东西:
- public MainPage()
- {
- this.InitializeComponent();
- Window.Current.VisibilityChanged += Current_VisibilityChanged;
- }
- void Current_VisibilityChanged(object sender,Windows.UI.Core.VisibilityChangedEventArgs e)
- {
- if (!e.Visible)
- {
- //Something useful
- }
- }
虽然它不会捕获Charms激活,但它应该适用于您提到的其他情况.