十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
如果是在自己的程序中,可以利用自身的按键事件,如果是全局键盘,那就要用到键盘hook技术了,比较复杂。
成都创新互联公司专业提供四川电信机房托管服务,为用户提供五星数据中心、电信、双线接入解决方案,用户可自行在线购买四川电信机房托管服务,并享受7*24小时金牌售后服务。
Private Sub Form_Load()
Label1.Caption = ""
Text1 = ""
End Sub
Private Sub Text1_KeyPress(KeyAscii As Integer)
If KeyAscii = 13 Then '回车键
Label1.Caption = 1
ElseIf KeyAscii = 8 Then '退格键
Label1.Caption = 2
Else '其他按键
Label1.Caption = 3
End If
Me.Cls
Print KeyAscii
End Sub
用API GetKeyboardState ,判断所有的键里哪些被按下了。
下面的是判断键盘灯的状态
Public Class NativeMethods
Private Shared keyState() As Byte
DllImport("user32.dll") _
Private Shared Function GetKeyboardState(ByVal keyState() As Byte) As Boolean
End Function
Private Shared Sub Update()
keyState = New Byte(256) {}
Dim result As Boolean = GetKeyboardState(keyState)
' Check for error:
If result = False Then
Debug.WriteLine("GetKeyBoardState error: " Marshal.GetLastWin32Error)
Throw New Exception("GetKeyBoardState error: " Marshal.GetLastWin32Error)
End If
End Sub
Public Enum LightState
Off
[On]
End Enum
' Example - the keyboard lights...
Public Shared ReadOnly Property CapsLockState() As LightState
Get
Update()
Dim isOn As Boolean = (keyState(Keys.CapsLock) = 1)
Return IIf(isOn, LightState.On, LightState.Off)
End Get
End Property
Public Shared ReadOnly Property NumLockState() As LightState
Get
Update()
Dim isOn As Boolean = (keyState(Keys.NumLock) = 1)
Return IIf(isOn, LightState.On, LightState.Off)
End Get
End Property
Public Shared ReadOnly Property ScrollLockState() As LightState
Get
Update()
Dim isOn As Boolean = (keyState(Keys.Scroll) = 1)
Return IIf(isOn, LightState.On, LightState.Off)
End Get
End Property
End Class
窗体内检测按键
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.KeyPreview = True '注册窗体的键盘事件
End Sub
在TextBox1中显示按键代码
Private Sub Form1_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown
TextBox1.Text = Str(e.KeyCode) + vbCrLf
End Sub
窗体没有焦点,用窗体监测键盘输入缓冲区可以解决,但这似乎可以用于监测用户输入内容,不要用于非法目的呀!所以就是知道也不会告诉你的。
Public Class Form1
Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress
If Not IsNumeric(e.KeyChar) Then '判断是否为数字
e.Handled = True ‘如果不是数字,取消操作,不显示字符
End If
End Sub
End Class
这样就好啦
选到TextBox1的keydown方法,然后val=keycode不行么?
焦点在哪个控件,哪个控件就会有keydown,没有焦点也就不会有。