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

问题描述 投票:-1回答:3
private void send_Click(object sender, RoutedEventArgs e)
{
    (Application.Current as App).Broadcast(new ChatMessage { Username = name.Text, Message = text.Text });
    text.Text = "";
}

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

c# xaml uwp
3个回答
1
投票

您可以在xaml文件中绑定键绑定,如下所示:

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

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


0
投票

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


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

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.