VB and VBA Users Source Code: Determining which Keys are currently pressed
[
Home
|
Contents
|
Search
|
Reply
| Previous | Next ]
VB/VBA Source Code
Determining which Keys are currently pressed
By:
Andrew Baker
Email (spam proof):
Email the originator of this post
Date:
Thursday, December 07, 2000
Hits:
5080
Category:
Windows API
Article:
To test if a key or combination of keys have been pressed, used the following function: Private Declare Function GetAsyncKeyState Lib "user32" (ByVal vKey As Long) As Integer 'Purpose : Test the Keyboard buffer to see which keys have been pressed 'Inputs : vKey1 The character or ascii value of the first key to test ' [vKey2] The character or ascii value of the second key to test ' To call using text use: ' Debug.Pring KeyPressed("S") 'Returns true if the user has the "S" keypressed ' To call using ASCII values use: ' Debug.Pring KeyPressed(vbKeyS) 'Returns true if the user has the "S" keypressed 'Outputs : Returns True if the specified Key/s where pressed 'Author : Andrew Baker 'Date : 07/12/2000 12:14 'Examples : To Find out if Control + Q has been pressed use: ' If KeyPressed(vbKeyControl ,vbKeyQ) Then ' or To Find out if Shift + Q has been pressed use: ' If KeyPressed(vbKeyShift ,vbKeyQ) Then ' or To Find out if Alt + Q has been pressed use: ' If KeyPressed(18,vbKeyQ) Then 'Revisions : Public Function KeyPressed(ByVal vKey1 As Variant, Optional ByVal vKey2 As Variant) As Boolean Dim bResult As Boolean 'Check First Key (need to call twice, the first call clears 'the keyboard buffer then second checks it's still pressed) On Error GoTo ErrFailed If VarType(vKey1) = vbString Then bResult = CBool(GetAsyncKeyState(Asc(vKey1))) bResult = CBool(GetAsyncKeyState(Asc(vKey1))) Else bResult = CBool(GetAsyncKeyState(vKey1)) bResult = CBool(GetAsyncKeyState(vKey1)) End If If IsMissing(vKey2) = False Then 'Check Second Key If VarType(vKey2) = vbString Then bResult = bResult And CBool(GetAsyncKeyState(Asc(vKey2))) bResult = bResult And CBool(GetAsyncKeyState(Asc(vKey2))) Else bResult = bResult And CBool(GetAsyncKeyState(vKey2)) bResult = bResult And CBool(GetAsyncKeyState(vKey2)) End If End If KeyPressed = bResult Exit Function ErrFailed: Debug.Print Err.Description Debug.Assert False End Function
Terms and Conditions
Support this site
Download a trial version of the Excel Workbook Rebuilder