Check if Keys is Letter/Digit/Special Symbol

后端 未结 6 2069
时光取名叫无心
时光取名叫无心 2021-01-02 18:45

I override ProcessCmdKey and when I get Keys argument, I want to check if this Keys is Letter or Digit or Special Symbol.

I ha

6条回答
  •  北荒
    北荒 (楼主)
    2021-01-02 19:02

    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:

    • KeyDown
    • KeyPress
    • KeyUp

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

提交回复
热议问题