我有一个游戏,我想在用户移动到另一个应用程序时暂停。 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
并且我在 上尝试了
,但它们不会触发。GotFocus
和 LostFocus
事件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/