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

前端之家收集整理的这篇文章主要介绍了c# – 识别Windows 8 Style(Metro)应用程序何时处于后台或失去焦点前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
每当用户移动到另一个应用程序时,我都会想要暂停一个游戏.例如,当选择超级按钮菜单时,用户Windows键,alt-tab按到另一个应用程序,单击另一个应用程序或任何其他会使应用程序失去焦点的应用程序.

当然这应该是微不足道的!我只有一个Page和一个Canvas,我在Canvas上尝试了GotFocus和LostFocus事件,但它们并没有激发.

我最接近的是在捕获指针后在CoreWindow上使用PointerCaptureLost.当选择了超级按钮菜单时,这适用于应用程序切换,但是当按下Windows键时这不起作用.

编辑:

在下面的Chris Bowen的帮助下,最终的“解决方案”如下:

  1. public MainPage() {
  2. this.InitializeComponent();
  3. CapturePointer();
  4. Window.Current.CoreWindow.PointerCaptureLost += PointerCaptureLost;
  5. Window.Current.CoreWindow.PointerPressed += PointerPressed;
  6. Window.Current.VisibilityChanged += VisibilityChanged;
  7. }
  8.  
  9. private void VisibilityChanged(object sender,VisibilityChangedEventArgs e) {
  10. if(e.Visible) {
  11. CapturePointer();
  12. }
  13. else {
  14. Pause();
  15. }
  16. }
  17.  
  18. void PointerPressed(CoreWindow sender,PointerEventArgs args) {
  19. CapturePointer();
  20. }
  21.  
  22. private void CapturePointer() {
  23. if(hasCapture == false) {
  24. Window.Current.CoreWindow.SetPointerCapture();
  25. hasCapture = true;
  26. }
  27. }
  28.  
  29. void PointerCaptureLost(CoreWindow sender,PointerEventArgs args) {
  30. hasCapture = false;
  31. Pause();
  32. }
  33.  
  34. private bool hasCapture;

它似乎仍然应该是一种更简单的方式,所以如果你发现更优雅的东西,请告诉我.

解决方法

尝试使用 Window.VisibilityChanged活动.像这样的东西:
  1. public MainPage()
  2. {
  3. this.InitializeComponent();
  4. Window.Current.VisibilityChanged += Current_VisibilityChanged;
  5. }
  6.  
  7. void Current_VisibilityChanged(object sender,Windows.UI.Core.VisibilityChangedEventArgs e)
  8. {
  9. if (!e.Visible)
  10. {
  11. //Something useful
  12. }
  13. }

虽然它不会捕获Charms激活,但它应该适用于您提到的其他情况.

猜你在找的C#相关文章