Detecting Mouse-Clicks Globally

CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

This code sample shows how to detect a mouse click anywhere on the desktop and on any window.

screen-shot

The code works by utilising the GetAsyncKeyState API call that can check the status of keyboard and mouse input at any point in a programs processing.

A form is used with a timer that fires every 10th of a second to check for the VK_LBUTTON and VK_RBUTTON keystates (the left and right mouse buttons).


option Explicit

private Declare Function GetAsyncKeyState Lib "user32" _
        (byval vKey as Long) as Integer
private Const VK_LBUTTON = &H1
private Const VK_RBUTTON = &H2

private Sub Form_Load()
    Timer1.Interval = 100
End Sub

private Sub Timer1_Timer()
    If GetAsyncKeyState(VK_LBUTTON) then
        Label2.Caption = "Left Click"
    ElseIf GetAsyncKeyState(VK_RBUTTON) then
        Label2.Caption = "Right Click"
    else
        Label2.Caption = ""
    End If
End Sub
'

Download Zipped Project (3k)

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read