Thursday, November 8, 2012


You can use the GetKeyState API to find out if the user is holding down a particular key. I've used this function to take me directly into the VBA code behind a command button while a form is in form view. This is very hand for debugging, but takes some setup. I check for the Ctl-Alt key combination in the OnMouseUp event property of the command button. My OnMouseUp event property looks like this:
In the declarations section of a standard module I put:
Const VK_LSHIFT = &HA0
Const VK_RSHIFT = &HA1
Const VK_LMENU = &HA4
Const VK_RMENU = &HA5
#If vba7 Then
    Declare PtrSafe Function GetKeyState Lib "user32" Alias "GetKeyState" (ByVal nVirtKey As Long) As Integer
    Declare Function GetKeyState Lib "user32" (ByVal nVirtKey As Long) As Integer
#End If
And the function looks like this:
Function xg_CtrlAltMouseUp() As Integer
'* Peter De Baets, author
'* 11/2/2012
Dim Marker As Integer
Dim Rtn As Integer

On Error GoTo Err_Section
Marker = 1

'Return values
'0 if the key is neither down nor toggled,
'-127 if the key is down but not toggled,
'1 if the key is toggled but up, and
'-128 if the key is both toggled and down.
If GetKeyState(VK_LCONTROL) < 0 And GetKeyState(VK_LMENU) < 0 Then
    DoCmd.OpenModule "Form_" & Screen.ActiveForm.Name, _
        Screen.ActiveControl.Name & "_Click"

End If

    On Error Resume Next
    On Error GoTo 0
    Exit Function
    Select Case Err
    Case Else
        MsgBox "Error in xg_CtrlAltMouseUp (" & Marker & "), _
        object " & Err.Source & ": " & Err.Number & _
        " - " & Err.Description
    End Select
    Resume Exit_Section
End Function

No comments: