c# – 识别Windows 8 Style(Metro)应用程序何时处于后台或失去焦点

每当用户移动到另一个应用程序时,我都会想要暂停一个游戏.例如,当选择超级按钮菜单时,用户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激活,但它应该适用于您提到的其他情况.

相关文章

目录简介使用JS互操作使用ClipLazor库创建项目使用方法简单测...
目录简介快速入门安装 NuGet 包实体类User数据库类DbFactory...
本文实现一个简单的配置类,原理比较简单,适用于一些小型项...
C#中Description特性主要用于枚举和属性,方法比较简单,记录...
[TOC] # 原理简介 本文参考[C#/WPF/WinForm/程序实现软件开机...
目录简介获取 HTML 文档解析 HTML 文档测试补充:使用 CSS 选...