简体   繁体   中英

Detect Numeric Keys in Textbox - VB.NET

I want to detect numeric keys of numpad in textbox keypress event, Actually I just want to allow user to enter numbers from numpad not from alphanumeric pad.

If the numbers are not coming from numpad of the keyboard, event should be cancel.

Is there any way except GetAsyncKeyState() to achieve this task?

Currently I'm trying this codes.

 If e.KeyChar = Chr(49) Then '48 to 57 are the char codes for "0 to 9" of alphanumeric keypad. 
    e.Handled = True 
 End I

The use GetAsyncKeyState() is my last priority because it can decrease the performance of my application.

There are two ways to check this

  1. To check for specific keys instead of characters, use the KeyCode property of the KeyDown/KeyUp events for values between Keys.NumPad0 to Keys.NumPad9. KeyPress doesn't provide this property.

     If (e.KeyCode >= Keys.NumPad0 and e.KeyCode <= Keys.NumPad9) Then ... 
  2. If you want to check whether a character is a numeric digit, you can use Char.IsDigit to check whether a character is a numeric digit. You can write:

     If Char.IsDigit(e.KeyChar) Then .... 

Keypad 0-9 is Keycode 96 to 105

      KEY        CODE
    ------------------
     numpad 0    96
     numpad 1    97
     numpad 2    98
     numpad 3    99
     numpad 4    100
     numpad 5    101
     numpad 6    102
     numpad 7    103
     numpad 8    104
     numpad 9    105

Key and Character Codes vs. Event Types
Guide for keycodes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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