Tuesday, July 12, 2011

Get Key Status :

How To Know HOT Key Status ... if they are pressed or Not??







'declare window API's Function
Declare Function GetKeyState Lib "user32" (ByVal nVirtKey As Long) As Integer

'   Constants for the keys of interest
    Const VK_SHIFT As Integer = &H10
    Const VK_CONTROL As Integer = &H11
    Const VK_MENU As Integer = &H12 'Alt key


Sub DisplayKeyStatus()
    Dim TabChar As String * 1
    Dim CRChar As String * 1
    Dim Shift As Boolean, Control As Boolean, Alt As Boolean
    Dim Msg As String
   
    TabChar = Chr(9)
    CRChar = Chr(13)

'   Use API calls to determine which keys are pressed
    If GetKeyState(VK_SHIFT) < 0 Then Shift = True Else Shift = False
    If GetKeyState(VK_CONTROL) < 0 Then Control = True Else Control = False
    If GetKeyState(VK_MENU) < 0 Then Alt = True Else Alt = False

'   Build the message
    Msg = "Shift:" & TabChar & Shift & CRChar
    Msg = Msg & "Control:" & TabChar & Control & CRChar
    Msg = Msg & "Alt:" & TabChar & Alt & CRChar
   
'   Display message box
    MsgBox Msg, vbInformation, "Key Status"
End Sub

2 comments:

Dog's Corner said...

Great work. I'd love to know how to obtain the status of the keypress within a loop rather than a msgbox...

for i = 1 to 1000
cells(1,1) = GetKeyState(VK_CONTROL)
next i

it will only show the initial value. i.e zero... the fact you have a msgbox, seems to interupt the code and allow the VK_CONTROL value to be passed.

Rajan said...

To Get the Result of HOT key Status use this
if you want to use a loop then put this code in a loop

'declare window API's Function
Declare Function GetKeyState Lib "user32" (ByVal nVirtKey As Long) As Integer

' Constants for the keys of interest
Const VK_SHIFT As Integer = &H10
Const VK_CONTROL As Integer = &H11
Const VK_MENU As Integer = &H12 'Alt key


Sub DisplayKeyStatus()
Dim TabChar As String * 1
Dim CRChar As String * 1
Dim Shift As Boolean, Control As Boolean, Alt As Boolean
Dim Msg As String

TabChar = Chr(9)
CRChar = Chr(13)

' Use API calls to determine which keys are pressed
If GetKeyState(VK_SHIFT) < 0 Then Shift = True Else Shift = False
If GetKeyState(VK_CONTROL) < 0 Then Control = True Else Control = False
If GetKeyState(VK_MENU) < 0 Then Alt = True Else Alt = False

' Build the message
Range("A1").Value = "Shift:" & TabChar & Shift & CRChar
Range("A2").Value = "Control:" & TabChar & Control & CRChar
Range("A3").Value = "Alt:" & TabChar & Alt & CRChar


End Sub