【问题标题】:Problems with KeyCode in c# UWPc# UWP中KeyCode的问题
【发布时间】:2016-06-20 08:57:45
【问题描述】:

我使用此代码来识别按下了哪个键,但是当我尝试识别箭头时,它没有显示任何内容,甚至没有激活TestFunction();

private void CoreWindow_CharacterReceived(CoreWindow sender, CharacterReceivedEventArgs args)
{
    if (args.KeyCode == 39) //Right Arrow
    {
        //Do somthing
        TestFunction();
    }
    else //Detect All arrows KeyCode(Never display anything for this keys)
    {
        Debug.Write(args.KeyCode.ToString());
    }
}

PD:我在执行时使用此代码:

Window.Current.CoreWindow.CharacterReceived += CoreWindow_CharacterReceived;

【问题讨论】:

  • 你确定你得到了这个方法的调试器吗?
  • 是的,我做到了,除了上、下、左、右、控制、alt 之外,我得到了所有的键

标签: c# windows key uwp keycode


【解决方案1】:

箭头不完全是一个字符。也许您应该考虑 KeyUpKeyDown 事件?

【讨论】:

  • 作为虚拟键?我已经试过了,结果是一样的。
  • 也许是焦点问题?看看这个链接social.msdn.microsoft.com/Forums/sqlserver/en-US/…
  • 也许吧,但是每个键都可以,我可以按空格或任何单词,但不能按箭头或控制键
  • 只是在答案中添加一些内容:我在想为什么 Backspace 会触发 CharacterReceived 事件。我猜除了 KeyDownKeyUp 事件之外,任何可以转换为 ASCII(Unicode?)字符的东西都会触发 CharacterReceived。 BackSpace 在 ASCII 中是 8。但是 Tab 和 Enter 是系统键,不会通过 CharacterReceived 事件
【解决方案2】:

但是每个键都可以,我可以按空格或任何单词,但箭头或控制键不行

CoreWindow.CharacterReceived 事件在输入队列接收到新的字符 时触发。 字符是用于表示文本、数字或符号的单个视觉对象。箭头或控制键不代表任何字符。因此,当这些键被按下时,CoreWindow.CharacterReceived 事件不会被触发

如果您想识别键盘上的哪个键(包括箭头和控制)以及其他不代表任何字符的键被按下,请使用 UIElement.KeyDownUIElement.KeyUp 事件(在按下/释放键盘键时发生UIElement 有焦点) 而不是上面提到的 kra。

以下是我验证过的简单代码:

MainPage.xaml:

<StackPanel VerticalAlignment="Center" HorizontalAlignment="Center">
    <!--Define a control which can have focus and accept input-->
    <TextBox Header="Get Focus and Press Any key on Keyboard" x:Name="txt1" KeyDown="txt1_KeyDown" />
</StackPanel>

MainPage.xaml.cs:

public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();
    }

    private async void txt1_KeyDown(object sender, KeyRoutedEventArgs e)
    {
        // Right Arrow key Pressed
        if (e.Key == Windows.System.VirtualKey.Right)
        {
            // Do something
            Debug.WriteLine(e.Key.ToString());
            await new MessageDialog(e.Key.ToString()).ShowAsync();
        }
        // Other Keys Pressed
        await new MessageDialog(e.Key.ToString()).ShowAsync();
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-20
    • 2019-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多