C# 如何从 WPF KeyDown 事件中获取正常字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/486927/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 05:19:46  来源:igfitidea点击:

How do I get the normal characters from a WPF KeyDown event?

c#wpfeventskeyboard

提问by Malcolm

I want the ASCII characters passed by the e.Keyproperty from a WPF KeyDownevent.

我想要e.Key属性从 WPFKeyDown事件传递的 ASCII 字符。

回答by Steven Robbins

Unfortunately there's no easy way to do this. There's 2 workarounds, but they both fall down under certain conditions.

不幸的是,没有简单的方法可以做到这一点。有两种解决方法,但它们都在某些条件下失败。

The first one is to convert it to a string:

第一个是将其转换为字符串:

TestLabel.Content = e.Key.ToString();

This will give you the things like CapsLock and Shift etc, but, in the case of the alphanumeric keys, it won't be able to tell you the state of shift etc. at the time, so you'll have to figure that out yourself.

这将为您提供 CapsLock 和 Shift 等功能,但是,对于字母数字键,它无法告诉您当时的换档状态等,因此您必须弄清楚这一点你自己。

The second alternative is to use the TextInput event instead, where e.Text will contain the actual text entered. This will give you the correct character for alphanumeric keys, but it won't give you control characters.

第二种选择是改用 TextInput 事件,其中 e.Text 将包含输入的实际文本。这将为您提供正确的字母数字键字符,但不会为您提供控制字符。

回答by Gishu

From your concise question, I'm assuming you need a way to get the ASCII value for the pressed key. This should work

从您的简洁问题来看,我假设您需要一种方法来获取按键的 ASCII 值。这应该工作

private void txtAttrName_KeyDown(object sender, KeyEventArgs e)
        {
            Console.WriteLine(e.Key.ToString());
            char parsedCharacter = ' ';
            if (Char.TryParse(e.Key.ToString(), out parsedCharacter))
            {
                Console.WriteLine((int) parsedCharacter);
            }
        }

e.g. if you press Ctrl + S, you'd see the following output.

例如,如果您按 Ctrl + S,您将看到以下输出。

LeftCtrl
S
83

回答by onur

System.Enum.ToObject(e.Key.GetType(), (byte)e.Key).ToString();

回答by Thomas AUGUEY

Can you use the TextInput event rather than KeyDown? the TextCompositionEventArgs class allows you to directly retrieve the text entered via the e.text property

您可以使用 TextInput 事件而不是 KeyDown 吗?TextCompositionEventArgs 类允许您直接检索通过 e.text 属性输入的文本

private void UserControl_TextInput(
    object sender, 
    System.Windows.Input.TextCompositionEventArgs e)
{
     var t = e.Text;
}