微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 检查键是否是字母/数字/特殊符号

我重写ProcessCmdKey,当我得到Keys参数时,我想检查这些键是字母还是数字还是特殊符号.

我有这个片段

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);
    }

一切都适用于字母和数字.但是当我按下F1-F12时,它会将它们转换成字母.

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

解决方法

改为覆盖表单的OnKeyPress方法. KeyPressEventArgs提供了一个 KeyChar属性,允许您在char上使用静态方法.

正如Cody Gray在评论中所提到的,这种方法只会触发具有角色信息的击键.其他击键如F1-F12应在OnKeyDown或OnKeyUp中处理,具体取决于您的情况.

MSDN开始:

Key events occur in the following
order:

  • 07002
  • 07003
  • 07004

The KeyPress event is not raised by
noncharacter keys
; however,the
noncharacter keys do raise the KeyDown
and KeyUp events.

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
  }
}

原文地址:https://www.jb51.cc/csharp/101051.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐