更新时间:2023-12-01 13:42:40
的OnKeyPress
方法,而不是在 KeyPressEventArgs
提供的 KeyChar
属性,它可以让你利用静态方法在字符
。 由于在评论中提到科迪灰色,这种方法只对有个性的击键火灾信息,其他击键如F1-F12应该被处理的onkeydown
或的onkeyup
,根据您的情况。
关键事件发生在以下
顺序:
的KeyPress事件不是由
非字符键上调;然而,
非字符键做提高的KeyDown
和KeyUp事件。
块引用>示例
保护覆盖无效的OnKeyPress(KeyPressEventArgs E)
{
base.OnKeyPress(E);
如果(char.IsLetter(e.KeyChar))
{
// char是字母
}
,否则如果(char.IsDigit(e.KeyChar))
{
// char是位
}
,否则
{
//字符既不是字母或数字。
//有更多可以用来确定
的方法// char类型的,例如char.IsSymbol
}
}
I override
ProcessCmdKey
and when I getKeys
argument, I want to check if thisKeys
is Letter or Digit or Special Symbol.I have this snippet
protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { char key = (char)keyData; if(char.IsLetterOrDigit(key) { Console.WriteLine(key); } return base.ProcessCmdKey(ref msg, keyData); }
Everything works for letters and digits. but when I press F1-F12 it converts them to letters.
Maybe someone knows better way to solve this task?
Override the form's
OnKeyPress
method instead. TheKeyPressEventArgs
provides aKeyChar
property which allows you to utilize the static methods onchar
.As mentioned by Cody Gray in the comments, this method only fires on key strokes that have character information. Other key strokes such as F1-F12 should be processed in
OnKeyDown
orOnKeyUp
, depending on your situation.From MSDN:
Key events occur in the following order:
The KeyPress event is not raised by noncharacter keys; however, the noncharacter keys do raise the KeyDown and KeyUp events.
Example
protected override void OnKeyPress(KeyPressEventArgs e) { base.OnKeyPress(e); if (char.IsLetter(e.KeyChar)) { // char is letter } else if (char.IsDigit(e.KeyChar)) { // char is digit } else { // char is neither letter or digit. // there are more methods you can use to determine the // type of char, e.g. char.IsSymbol } }