VB and VBA Users Source Code: Testing Virtual Key states (inc. Mouse Buttons)
[
Home
|
Contents
|
Search
|
Reply
| Previous | Next ]
VB/VBA Source Code
Testing Virtual Key states (inc. Mouse Buttons)
By:
Andrew Baker
Email (spam proof):
Email the originator of this post
Date:
Wednesday, October 09, 2002
Hits:
1625
Category:
Windows API
Article:
The following code demonstrates how to detect if any of the 256 virtual keys have been pressed (including mouse buttons). Option Explicit 'Uncomment this for VBA 'Private Const vbLeftButton As Long = 1 'Private Const vbRightButton As Long = 2 'Private Const vbMiddleButton As Long = 4 Private Type KeyboardBytes abKeys(0 To 255) As Byte End Type Private Declare Function GetKeyboardState Lib "user32" (kbArray As KeyboardBytes) As Long 'Purpose : Tests to see the state of the 256 virtual keys. 'Inputs : bKey The Key to test the state of eg vbKeyF2, vbKeyA, vbKeyReturn or vbLeftButton (for left button mouse down) etc 'Outputs : Returns True if the specified Key is pressed 'Author : Andrew Baker 'Date : 07/12/2000 12:14 'Notes : 'Revisions : Public Function VirtualKeyPressed(bKey As Byte) As Boolean Dim abKeyStates As KeyboardBytes GetKeyboardState abKeyStates VirtualKeyPressed = (abKeyStates.abKeys(bKey) > 1) End Function 'Demonstration routine Sub Test() 'Test to see if the left mouse button is pressed If VirtualKeyPressed(vbLeftButton) Then 'In VBA use 1,2,3 for the Left, Right and Middle mouse buttons respectively MsgBox "Your left mouse button is pressed" End If 'Test to see if the Caps Lock button is pressed If VirtualKeyPressed(vbKeyCapital) Then MsgBox "Your Caps Lock is pressed" End If End Sub
Terms and Conditions
Support this site
Download a trial version of the Excel Workbook Rebuilder