A method to get the pixel color under the mouse pointer

This small code sample shows how to obtain the RGB color of any pixel under the cursor.


The code uses a timer control to fire events ever 100’th of a second and then uses the GetPixel, GetCursorPos, and GetDC WinAPI calls to obtain the value.

option Explicit
'Aaron Young
'Analyst Programmer
'[email protected] <mailto:[email protected]>

'Add a Timer Control to a Form, then use this code And point to
'anywhere on your screen to have
'the RGB value appear In the Forms Caption.
private Type POINTAPI
    x as Long
    y as Long
End Type
private Declare Function GetPixel Lib "gdi32" (byval hdc as Long, _
    byval x as Long, byval y as Long) as Long
private Declare Function GetCursorPos Lib "user32" _
        (lpPoint as POINTAPI) as Long
private Declare Function GetWindowDC Lib "user32" (byval hwnd as Long) _
        as Long
private Sub Form_Load()
    Timer1.Interval = 100
End Sub
private Sub Timer1_Timer()
    Dim tPOS as POINTAPI
    Dim sTmp as string
    Dim lColor as Long
    Dim lDC as Long
    lDC = GetWindowDC(0)
    Call GetCursorPos(tPOS)
    lColor = GetPixel(lDC, tPOS.x, tPOS.y)
    Label2.BackColor = lColor
    sTmp = Right$("000000" & Hex(lColor), 6)
    Caption = "R:" & Right$(sTmp, 2) & " G:" &_
         mid$(sTmp, 3, 2) & " B:" & Left$(sTmp, 2)
End Sub

Download zipped project file

More by Author

Must Read