Get Color of a Pixel Given Current Mouse Location (i.e.  RGB color of X,Y)

Posted on 2004-10-25
Last Modified: 2010-04-23
I've looked everywhere.  Given the coordinates of a point on the screen (such as 185,185), how do
you get the color of said point using VB.NET 2003.

I have looked EVERYWHERE for this, but to no avail.  All the examples I've
seen use old code that is no longer supported in .NET.

For example, there are numerous places that have quoted the routine:
Private Type POINTAPI
    X As Long
    Y As Long
End Type

since TYPE is not supported in .NET 2003, it doesn't help.

I got most of the following  code here from experts exchange, but it doesn't work-  it just keeps
giving me the same dozen digit number over and over again (which has no
meaning to me).  The Mouse Position works great.  The code grabs the position of the mouse.  But it never returns any color other than RGB= 127,254,3.  AM I doing something wrong?  I'm quite desperate.

Please remember, I'm on VB.NET 2003.  Old VB code just doesn't work in this version

Public Class Form1

    Inherits System.Windows.Forms.Form
    Public Structure POINTAPI
        Public X As Long
        Public Y As Long
    End Structure
    Public Declare Function GetCursorPos Lib "USER32.dll" (ByVal lpPoint As POINTAPI) As Long
    Public Declare Function GetPixel Lib "gdi32.dll" (ByVal hdc As Long, ByVal nXPos As Long, ByVal nYPos As Long) As Long
    Public Declare Function ReleaseDC Lib "user32.dll" (ByVal hWnd As Long, ByVal hdc As Long) As Long
    Public Declare Function GetDC Lib "user32" (ByVal hWnd As Long) As Long
    Public Declare Function GetDesktopWindow Lib "USER32.dll" () As Long
    Private lDesktopDC As Long

#Region " Windows Form Designer generated code "

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    End Sub

    Private Sub Form1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseMove

        Dim mXY As POINTAPI, mHc As Long, rgbV As Long, mDC As Long
        Dim R As Byte, G As Byte, B As Byte, rv, ry
        Dim oXY As POINTAPI, HexVal As String
        Dim color
        rv = Cursor.Position.X 'get mouse position X
        ry = Cursor.Position.Y 'get mouse position Y
        mHc = GetDesktopWindow() 'get a handle to screen
        rgbV = GetPixel(GetDC(0), rv, ry)
        '---convert color value from long to hex/rgb-----------------------
        HexVal = Hex(Val(rgbV))

        R = CLng("&H" + Mid(HexVal, 1, 2)) 'red color value
        G = CLng("&H" + Mid(HexVal, 3, 2)) 'green color value
        B = CLng("&H" + Mid(HexVal, 5, 2)) 'blue color value
        '--display information-----------------------------------------------

        TextBox1.Text = "RGB= " & R & "," & G & "," & B 'show RGB values
        TextBox2.Text = rgbV
        ReleaseDC(mHc, mDC) ' release device context

    End Sub

End Class

This code above does not work.  My real goal is to be able to grab the color of a mouse location on another application.  I'd like to do this:
AppActivate ("MyApp")
GetPixel (x,y) 'return the color of a pixel on the other application

I've spent hours in goolge and on here looking for a way to do this, but all code examples I've found are in older versions of .NET and generate errors.
Question by:panspermia
    LVL 85

    Accepted Solution

    How about this approach?

    Public Class Form1
        Inherits System.Windows.Forms.Form

    #Region " Windows Form Designer generated code "

        Public Sub New()

            'This call is required by the Windows Form Designer.

            'Add any initialization after the InitializeComponent() call

        End Sub

        'Form overrides dispose to clean up the component list.
        Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
            If disposing Then
                If Not (components Is Nothing) Then
                End If
            End If
        End Sub

        'Required by the Windows Form Designer
        Private components As System.ComponentModel.IContainer

        'NOTE: The following procedure is required by the Windows Form Designer
        'It can be modified using the Windows Form Designer.  
        'Do not modify it using the code editor.
        Friend WithEvents Timer1 As System.Windows.Forms.Timer
        Friend WithEvents NotifyIcon1 As System.Windows.Forms.NotifyIcon
        Friend WithEvents Timer2 As System.Windows.Forms.Timer
        Friend WithEvents Label1 As System.Windows.Forms.Label
        Friend WithEvents Label2 As System.Windows.Forms.Label
        <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
            Me.components = New System.ComponentModel.Container
            Me.Timer1 = New System.Windows.Forms.Timer(Me.components)
            Me.NotifyIcon1 = New System.Windows.Forms.NotifyIcon(Me.components)
            Me.Timer2 = New System.Windows.Forms.Timer(Me.components)
            Me.Label1 = New System.Windows.Forms.Label
            Me.Label2 = New System.Windows.Forms.Label
            Me.Timer1.Interval = 25
            Me.NotifyIcon1.Text = "RubberBand Screen Capture Demo"
            Me.Timer2.Enabled = True
            Me.Label1.Location = New System.Drawing.Point(8, 8)
            Me.Label1.Name = "Label1"
            Me.Label1.Size = New System.Drawing.Size(232, 24)
            Me.Label1.TabIndex = 0
            Me.Label1.Text = "Label1"
            Me.Label2.Location = New System.Drawing.Point(8, 48)
            Me.Label2.Name = "Label2"
            Me.Label2.Size = New System.Drawing.Size(232, 24)
            Me.Label2.TabIndex = 1
            Me.Label2.Text = "Label2"
            Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
            Me.ClientSize = New System.Drawing.Size(448, 286)
            Me.Name = "Form1"
            Me.Text = "GetPixel Color Demo"

        End Sub

    #End Region

        Private Const SRCCOPY = &HCC0020

        Private Declare Function CreateDC Lib "gdi32" Alias "CreateDCA" (ByVal lpDriverName As String, ByVal lpDeviceName As String, ByVal lpOutput As String, ByVal lpInitData As String) As Integer
        Private Declare Function CreateCompatibleDC Lib "GDI32" (ByVal hDC As Integer) As Integer
        Private Declare Function CreateCompatibleBitmap Lib "GDI32" (ByVal hDC As Integer, ByVal nWidth As Integer, ByVal nHeight As Integer) As Integer
        Private Declare Function SelectObject Lib "GDI32" (ByVal hDC As Integer, ByVal hObject As Integer) As Integer
        Private Declare Function BitBlt Lib "GDI32" (ByVal hDestDC As Integer, ByVal X As Integer, ByVal Y As Integer, ByVal nWidth As Integer, ByVal nHeight As Integer, ByVal hSrcDC As Integer, ByVal SrcX As Integer, ByVal SrcY As Integer, ByVal Rop As Integer) As Integer
        Private Declare Function DeleteObject Lib "GDI32" (ByVal hObj As Integer) As Integer
        Private Declare Function DeleteDC Lib "GDI32" (ByVal hDC As Integer) As Integer

        Private Function GetScreen(ByVal X As Integer, ByVal Y As Integer, ByVal Width As Integer, ByVal Height As Integer) As Bitmap
            Dim hDeskDC As Integer
            Dim hTempDC As Integer
            Dim hBitmap As Integer
            Dim hTempBmp As Integer
            Dim desktopArea As Bitmap

            hDeskDC = CreateDC("DISPLAY", "", "", "")
            If hDeskDC Then
                hTempDC = CreateCompatibleDC(hDeskDC)
                If hTempDC Then
                    hBitmap = CreateCompatibleBitmap(hDeskDC, Width, Height)
                    If hBitmap Then
                        hTempBmp = SelectObject(hTempDC, hBitmap)
                        BitBlt(hTempDC, 0, 0, Width, Height, hDeskDC, X, Y, SRCCOPY)
                        desktopArea = Bitmap.FromHbitmap(New IntPtr(hBitmap))
                        DeleteObject(SelectObject(hTempDC, hTempBmp))
                    End If
                End If
            End If
            Return desktopArea
        End Function

        Private Sub Timer2_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer2.Tick
            Static x As Integer
            Static y As Integer
            If Cursor.Position.X <> x Or Cursor.Position.Y <> y Then
                x = Cursor.Position.X
                y = Cursor.Position.Y
                Dim b As Bitmap = GetScreen(0, 0, Screen.PrimaryScreen.WorkingArea.Width, Screen.PrimaryScreen.WorkingArea.Height)
                Label1.Text = x & ", " & y
                Label2.Text = b.GetPixel(x, y).ToString
            End If
        End Sub

    End Class

    Author Comment

    You ROCK man.  You are the best.  5 stars!!!!  Thank you so much.

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    How to improve team productivity

    Quip adds documents, spreadsheets, and tasklists to your Slack experience
    - Elevate ideas to Quip docs
    - Share Quip docs in Slack
    - Get notified of changes to your docs
    - Available on iOS/Android/Desktop/Web
    - Online/Offline

    Suggested Solutions

    A while ago, I was working on a Windows Forms application and I needed a special label control with reflection (glass) effect to show some titles in a stylish way. I've always enjoyed working with graphics, but it's never too clever to re-invent …
    It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
    This video Micro Tutorial is the first in a two-part series that shows how to create and use custom scanning profiles in Nuance's PaperPort 14.5 ( But the ability to create custom scanning profiles al…
    Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…

    884 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    18 Experts available now in Live!

    Get 1:1 Help Now