我有一个游戏,当用户移动到另一个应用程序时,我想暂停它。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.
当然,这应该是微不足道的!我只有 aPage
和 aCanvas
并且我在 上尝试了GotFocus
和LostFocus
事件Canvas
,但它们不会触发。
我最接近的是PointerCaptureLost
在CoreWindow
捕获指针后使用。这适用于选择魅力菜单时的应用程序切换,但当按下 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;
似乎它们仍然应该是一种更简单的方法,所以如果您发现更优雅的方法,请告诉我。