2016-06-07 73 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應用程序。 –