Determine when Windows 8 Style (Metro) is in the background or focus is lost

I have a game that I want to pause whenever a user navigates to another application. For example, when the enchantment menu is selected, the user presses the Windows key, Alt-Tab on another application, clicks on another application or something else that might cause the application to lose focus.

Of course, this should be trivial! I only have Page and Canvas , and I tried the GotFocus and LostFocus on Canvas , but they do not fire.

The closest I came using PointerCaptureLost on CoreWindow after capturing the pointer. This works for switching applications when the charms menu is selected, but it does not work when the Windows key is pressed.

EDIT:

With the help of Chris Bowen below, the final β€œsolution” is as follows:

 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; 

It still seems like they should be easier, so please let me know if you find something more elegant.

+6
source share
2 answers

Try using the Window.VisibilityChanged event. Something like that:

 public MainPage() { this.InitializeComponent(); Window.Current.VisibilityChanged += Current_VisibilityChanged; } void Current_VisibilityChanged(object sender, Windows.UI.Core.VisibilityChangedEventArgs e) { if (!e.Visible) { //Something useful } } 

Although it will not activate Charms, it should work for other cases that you mentioned.

+6
source

Try using the onSuspending event, predefined in App.xaml.cs, to handle pausing your game. The event fires whenever the application is paused, so it can work. You may need to perform checks, for example, make sure that the game is actually running before you try to pause it, because this event fires when any page in the application pauses.

0
source

Source: https://habr.com/ru/post/926576/


All Articles