Happy Codings - Programming Code Examples
Html Css Web Design Sample Codes CPlusPlus Programming Sample Codes JavaScript Programming Sample Codes C Programming Sample Codes CSharp Programming Sample Codes Java Programming Sample Codes Php Programming Sample Codes Visual Basic Programming Sample Codes


Visual Basic Programming Code Examples

Visual Basic > Other Code Examples

Determining which Keys are currently pressed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
Determining which Keys are currently pressed 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 '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