检测文本框中的数字键 - VB.NET

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25419858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 18:04:57  来源:igfitidea点击:

Detect Numeric Keys in Textbox - VB.NET

.netvb.net

提问by Muhammad Saqib

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?

除了GetAsyncKeyState()完成这个任务,还有什么办法吗?

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.

使用GetAsyncKeyState()是我最后的优先事项,因为它会降低我的应用程序的性能。

回答by Panagiotis Kanavos

There are two ways to check this

有两种方法可以检查这个

  1. To check for specific keys instead of characters, use the KeyCodeproperty of the KeyDown/KeyUp events for values between Keys.NumPad0to 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.IsDigitto check whether a character is a numeric digit. You can write:

    If Char.IsDigit(e.KeyChar) Then ....
    
  1. 要检查特定键而不是字符,请使用KeyDown/KeyUp 事件的KeyCode属性获取Keys.NumPad0到 Keys.NumPad9之间的值。KeyPress 不提供此属性。

    If (e.KeyCode >= Keys.NumPad0 and e.KeyCode <= Keys.NumPad9) Then ...
    
  2. 如果要检查字符是否为数字,可以使用Char.IsDigit来检查字符是否为数字。你可以写:

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

回答by Vivek S.

Keypad 0-9 is Keycode 96 to 105

键盘 0-9 是 Keycode 96 到 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

键码和字符码 vs. 事件类型
指南