简体   繁体   English

如何在C#中找到字符的键代码?

[英]How do I find the key code of a character in C#?

Microsoft provides a documentation for key codes of characters. Microsoft提供了有关字符键代码文档 For example, one can find that the key code for the delete key is 8 whereas the add key (+) has the key code 107. In a Windows Forms Application I'm trying to create a text box that will only accept digits and the plus sign (+). 例如,人们可以发现删除键的键代码为8,而添加键(+)的键代码为107。在Windows窗体应用程序中,我试图创建一个仅接受数字和加号(+)。 To do this I have implemented the following code: 为此,我实现了以下代码:

private void ansBox_KeyPress(object sender, KeyPressEventArgs e)
{
   char ch = e.KeyChar;
   if (!Char.IsDigit(ch) && ch != 8 && ch != 107) e.Handled = true;
}

The code successfully disallows all input except for digits and deletion, but to my surprise blocks the use of the plus sing (+). 该代码成功地禁止了除数字和删除之外的所有输入,但令我惊讶的是,它阻止了加号(+)的使用。 This leads me to believe that "107" is not the key code for the plus sign in C# or that I've implemented the key codes incorrectly. 这使我相信“​​ 107”不是C#中加号的键代码,或者我没有正确实现键代码。 Is there a way to find the key codes of characters programmatically similarly to how variable types can be identified so that the key code of the plus character can be determined? 有什么方法可以类似于识别变量类型那样以编程方式找到字符的键码,从而可以确定加号字符的键码? Alternatively, have I done something incorrectly when trying to implement the above described text box functionality? 另外,尝试实现上述文本框功能时,我做错了什么吗?

KeyCode and KeyChar is not the same. KeyCodeKeyChar不相同。

KeyCode is a property of KeyEventArgs and provides data for the KeyDown and KeyUp events. KeyCodeKeyEventArgs的属性,并为KeyDownKeyUp事件提供数据。 It has the type Keys , which is an enum . 它具有Keys类型,它是一个enum

KeyChar is a property of KeyPressEventArgs and provides data for the KeyPress event. KeyCharKeyPressEventArgs的属性,并提供KeyPress事件的数据。 It is a char . 它是一个char

The numeric codes of the two are often different. 两者的数字代码通常是不同的。

You can simply test for the plus sign like this 您可以像这样简单地测试加号

ch != '+'

C# has an escape sequnce for Backspace ( '\\b' == (char)8 ) C#具有Backspace的转义序列'\\b' == (char)8

if (!Char.IsDigit(ch) && ch != '\b' && ch != '+') e.Handled = true;

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

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