如果是在自己的程序中,可以利用自身的按鍵事件,如果是全局鍵盤,那就要用到鍵盤hook技術(shù)了,比較復(fù)雜。
成都創(chuàng)新互聯(lián)公司專業(yè)提供四川電信機(jī)房托管服務(wù),為用戶提供五星數(shù)據(jù)中心、電信、雙線接入解決方案,用戶可自行在線購買四川電信機(jī)房托管服務(wù),并享受7*24小時金牌售后服務(wù)。
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?,判斷所有的鍵里哪些被按下了。
下面的是判斷鍵盤燈的狀態(tài)
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
窗體內(nèi)檢測按鍵
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
窗體沒有焦點(diǎn),用窗體監(jiān)測鍵盤輸入緩沖區(qū)可以解決,但這似乎可以用于監(jiān)測用戶輸入內(nèi)容,不要用于非法目的呀!所以就是知道也不會告訴你的。
Public?Class?Form1
Private?Sub?TextBox1_KeyPress(sender?As?Object,?e?As?KeyPressEventArgs)?Handles?TextBox1.KeyPress
If?Not?IsNumeric(e.KeyChar)?Then????'判斷是否為數(shù)字
e.Handled?=?True????‘如果不是數(shù)字,取消操作,不顯示字符
End?If
End?Sub
End?Class
這樣就好啦
選到TextBox1的keydown方法,然后val=keycode不行么?
焦點(diǎn)在哪個控件,哪個控件就會有keydown,沒有焦點(diǎn)也就不會有。