检查按键是字母/数字/特殊符号 [英] Check if Keys is Letter/Digit/Special Symbol

查看:197
本文介绍了检查按键是字母/数字/特殊符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我重写 ProcessCmdKey 键,当我得到的说法,我要检查,如果这是字母或数字或特殊符号。



我有这个片段

 保护覆盖布尔ProcessCmdKey(参考消息味精,钥匙KEYDATA)
{
字符键=(char)的KEYDATA;
如果(char.IsLetterOrDigit(键)
{
Console.WriteLine(键);
}
返回base.ProcessCmdKey(REF味精,KEYDATA);
}

一切工作的字母和数字。但是当我按下F1-F12是将它们转换成字母。



也许有人知道更好的办法来解决这个任务?


解决方案
< 。p>覆盖表单的的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 get Keys argument, I want to check if this Keys 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. The KeyPressEventArgs provides a KeyChar property which allows you to utilize the static methods on char.

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 or OnKeyUp, 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
  }
}

这篇关于检查按键是字母/数字/特殊符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆