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

标签 c# focus windows-8 microsoft-metro

我有一个游戏,我想在用户移动到另一个应用程序时暂停。 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.

当然这应该是微不足道的!我只有一个 Page 和一个 Canvas 并且我在 上尝试了 GotFocusLostFocus 事件Canvas,但它们不会触发。

我最接近的是在捕获指针后在 CoreWindow 上使用 PointerCaptureLost。这适用于选择 super 按钮菜单时的应用程序切换,但在按下 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 激活,但它应该适用于您提到的其他情况。

关于c# - 识别 Windows 8 风格 (Metro) 应用程序何时处于后台或失去焦点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12651566/

相关文章:

c# - 无法使用 autofac 解决通用存储库的依赖关系

javascript - 将焦点放在 Angular 模板/路线/表单中的文本输入上

Java SWT : Disable focus to 1st window until 2nd window closed

c++ - Windows 8 : Application is not able write to C:\ProgramData\

c# - 对象及其子对象上的 Web API 2 : how to return JSON with camelCased property names,

c# - 如何在 .NET Webforms 中使用 Jquery AJAX 将数据发布到 MySQL

ruby-on-rails-3 - Twitter Bootstrap 标签 : Go to Specific Tab on Page load

css - 在允许平移 [TOUCHSCREEN] 的同时禁用捏合以放大 IE10

windows - 我删除了 AppData/Packages 中的文件,一些应用程序无法运行

c# - Microsoft.ReportViewer.WinForms.V15 与 .NET Core 3.1 不兼容 - 如何在 WPF Core 中显示 RDLC?