简体   繁体   English

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

[英]How to catch physical keyboard input and in C#?

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

This is my click event but I'm tired of moving my cursor to click it.这是我的点击事件,但我厌倦了移动光标来点击它。 Is there any way to set the enter button to active this event?有没有办法设置回车按钮来激活这个事件?

You can bind the key bindings in the xaml file as follows:您可以按如下方式绑定 xaml 文件中的键绑定:

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

EnterKeyPressCommand: This can be a DelegateCommand in the code behind or view model whatever is the DataContext of your view. EnterKeyPressCommand:这可以是隐藏代码或视图模型中的 DelegateCommand,无论您的视图的 DataContext 是什么。

您可以在文本框中添加 KeyDown 事件,并在按下“Enter”时触发 send_Click 事件。

Just capture the KeyDown event handle for the container you want to capture the input for, and then to judge if the input virtual key is Enter .只需捕获要为其捕获输入的容器的KeyDown事件句柄,然后判断输入的虚拟键是否为Enter For example, the following demo capture the keyboard inputs for CoreWindow .例如,以下演示捕获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 = "";
    }
}

More details please reference Keyboard events .更多细节请参考键盘事件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM