2016-06-07 72 views
1

我使用的示例代码Busy.xaml显示ModalDialogTemplate10(UWP)使用ESC键关闭ModalDialog

public static void SetBusy(bool busy, string text = null) 
    { 
     WindowWrapper.Current().Dispatcher.Dispatch(() => 
     { 
      var modal = Window.Current.Content as ModalDialog; 
      var view = modal.ModalContent as Busy; 
      if (view == null) 
       modal.ModalContent = view = new Busy(); 
      modal.IsModal = view.IsBusy = busy; 
      view.BusyText = text; 
      modal.CanBackButtonDismiss = true; 
     }); 
    } 

我可以用ALT+Left Arrow关闭此对话框,但在大多数桌面应用程序按ESC键通常会也关闭弹出或对话框。

我尝试添加代码来处理KeyDownBusy.xaml,但是当我按ESC或任何键时,此方法从未执行过。

 private void UserControl_KeyDown(object sender, KeyRoutedEventArgs e) 
    { 
     if (e.Key == VirtualKey.Escape) 
     { 
      e.Handled = true; 
      SetBusy(false); 
     } 
    } 

那么,如何使这个ModalDialog接近时用户按ESC键?

+0

我已经编辑我的问题,谢谢。 –

+0

@AskTooMuch请注意您的用例:除了处理键盘上的“转义”外,您可能还想处理XBox控制器上的“B”按钮以及手机和平板电脑等移动设备上的“硬件后退按钮”。 – Herdo

+0

我测试过了,这些场景中的大部分都是由Template10处理的,我无法确认它是否处理XBOX上的“B”按钮,因为我没有XBOX设备来测试,但是感谢让我知道这个问题。 –

回答

1

你必须将事件处理程序附加到CharacterReceived事件CoreWindow

修改SetBusy方法:

public static void SetBusy(bool busy, string text = null) 
{ 
    WindowWrapper.Current().Dispatcher.Dispatch(() => 
    { 
     var modal = Window.Current.Content as ModalDialog; 
     var view = modal.ModalContent as Busy; 
     if (view == null) 
      modal.ModalContent = view = new Busy(); 
     modal.IsModal = view.IsBusy = busy; 
     view.BusyText = text; 
     modal.CanBackButtonDismiss = true; 

     // Attach to key inputs event 
     var coreWindow = Window.Current.CoreWindow; 
     coreWindow.CharacterReceived += CoreWindow_CharacterReceived; 
    }); 
} 

凡为CoreWindow_CharacterReceived是这样的:

private static void CoreWindow_CharacterReceived(CoreWindow sender, 
               CharacterReceivedEventArgs args) 
{ 
    // KeyCode 27 = Escape key 
    if (args.KeyCode != 27) return; 

    // Detatch from key inputs event 
    var coreWindow = Window.Current.CoreWindow; 
    coreWindow.CharacterReceived -= CoreWindow_CharacterReceived; 

    // TODO: Go back, close window, confirm, etc. 
} 
0

虽然模式是开放的只是使用的东西沿着这条路线:

private void Modal_KeyDown(object sender, KeyEventArgs e) 
{ 
    if (e.KeyCode == Keys.Escape) 
    { 
     this.Close(); 
    } 
} 

另一种方式来解决(e.KeyCode==Keys.Escape)是:

(e.KeyChar == (char)27) 

e.KeyCode==(char)Keys.Escape 

对于此代码工作,你需要Form.KeyPreview = true;

欲了解更多关于什么是上面:https://msdn.microsoft.com/en-us/library/system.windows.forms.control.keydown.aspx

我认为,你需要追加CancelButton属性使其正常工作。

(几乎同样的方法),我相信这应该很好的工作还有:

private void HandleEsc(object sender, KeyEventArgs e) 
{ 
    if (e.Key == Key.Escape) 
     Close(); 
} 

这是一个控制台应用程序:

if (Console.ReadKey().Key == ConsoleKey.Escape) 
{ 
    return; 
} 
+0

谢谢,我已经试过但不起作用(请参阅我更新的问题)。 –

+0

@AskTooMuch我编辑了我的答案,看看是否有帮助! – NoReceipt4Panda

+0

谢谢,但我在Windows 10和Template10库中使用UWP,而不是Clasic Desktop应用程序。 –