如何捕获物理键盘输入和C#?

时间:2018-02-28 06:40:54

标签: c# xaml uwp

private void send_Click(object sender, RoutedEventArgs e)
{
    (Application.Current as App).Broadcast(new ChatMessage { Username = name.Text, Message = text.Text });
    text.Text = "";
}

这是我的点击事件,但我已经厌倦了移动光标来点击它。 有没有办法设置回车按钮来激活此事件?

3 个答案:

答案 0 :(得分:1)

您可以按如下方式绑定xaml文件中的键绑定:

<Window.InputBindings>
    <KeyBinding Key="Return" Command="{Binding EnterKeyPressCommand}"/>
</Window.InputBindings>

EnterKeyPressCommand:这可以是代码隐藏或视图模型中的DelegateCommand,无论您的视图是什么DataContext。

答案 1 :(得分:0)

您可以在文本框中添加KeyDown事件,并在&#39;输入&#39;之后触发send_Click事件。被按下了。

答案 2 :(得分:0)

只需捕获要捕获输入的容器的KeyDown事件句柄,然后判断输入virtual key是否为Enter。例如,以下演示捕获CoreWindow的键盘输入。

public MainPage()
{
    this.InitializeComponent();
    Window.Current.CoreWindow.KeyDown += CoreWindow_KeyDown;
}

private void CoreWindow_KeyDown(Windows.UI.Core.CoreWindow sender, Windows.UI.Core.KeyEventArgs args)
{           
    if (args.VirtualKey == VirtualKey.Enter)
    {
        System.Diagnostics.Debug.WriteLine(args.VirtualKey.ToString());
        //(Application.Current as App).Broadcast(new ChatMessage { Username = name.Text, Message = text.Text });
        //text.Text = "";
    }
}

更多详情请参阅Keyboard events