(UWP)使用ESC键关闭ModalDialog

时间:2016-06-07 17:05:55

标签: c# xaml uwp template10

我在ModalDialog中使用示例代码Busy.xaml显示Template10

    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键通常也会关闭弹出窗口或对话框。

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

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

那么,当用户按下ModalDialog键时,如何关闭此ESC

2 个答案:

答案 0 :(得分:3)

您必须将事件处理程序附加到CharacterReceived的{​​{1}}事件。

修改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

答案 1 :(得分: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;
}