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
'ajyoung@pressenter.com <mailto:ajyoung@pressenter.com>

'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


  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • As all sorts of data becomes available for storage, analysis and retrieval - so called 'Big Data' - there are potentially huge benefits, but equally huge challenges...
  • The agile organization needs knowledge to act on, quickly and effectively. Though many organizations are clamouring for "Big Data", not nearly as many know what to do with it...
  • Cloud-based integration solutions can be confusing. Adding to the confusion are the multiple ways IT departments can deliver such integration...

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date