Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identify when Windows 8 Style (Metro) application is in background or lost focus

I've got a game that I want to pause whenever the user moves to another application. For example, when the charms menu is selected, the user presses the windows key, alt-tab to another application, click on another application or anything else that would make the application lose focus.

Of course this should be trivial! I only have a Page and a Canvas and I've tried GotFocus and LostFocus events on the Canvas, but they don't fire.

The closest I've come is using PointerCaptureLost on CoreWindow after capturing the pointer. This works for application switching when the charms menu is selected, but this does not work when the windows key is pressed.

EDIT:

With the help of Chris Bowen below, the final 'solution' is the following:

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 that their should be an easier way, so please let me know if you find something more elegant.

like image 905
Adrian Avatar asked Sep 29 '12 09:09

Adrian


1 Answers

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

public MainPage()
{
    this.InitializeComponent();
    Window.Current.VisibilityChanged += Current_VisibilityChanged;
}

void Current_VisibilityChanged(object sender, Windows.UI.Core.VisibilityChangedEventArgs e)
{
    if (!e.Visible) 
    {
        //Something useful
    }
}

Though it won't catch Charms activation, it should work for the other cases you mentioned.

like image 154
Chris Bowen - MSFT Avatar answered Oct 07 '22 00:10

Chris Bowen - MSFT