2

我正在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那么,当用户按下ESCkey时如何关闭它?

4

2 回答 2

3

您必须将事件处理程序附加CharacterReceivedCoreWindow.

修改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.
}
于 2016-06-07T20:20:48.197 回答
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;
}
于 2016-06-07T17:12:44.137 回答