tags:

views:

895

answers:

3

How can I get the color of a pixel at the location of the cursor? I know how to get the mouses position using MousePosition but I can not figure out how to get the pixel color at that location.

A: 

This is actually harder than you would guess. I would look for some example code that already does it, and copy their technique.

In the end, the algorithm is going to have to perform these operations:

  1. Get a bitmap of the desktop/window close to the cursor position
  2. Index into that bitmap with the cursor position and extract the pixel color

It sounds simple, but is not easy.

Frank Krueger
That is what I've been seeing but the only sample code I have been able to find is for C++ and I don't understand most of it.
Bryan
+4  A: 

A C# version: How do I get the colour of a pixel at X,Y using c# ?
Should be easy to rewrite in VB.NET.

Moayad Mardini
+1 There are tools that convert C# to VB.Net (at least to some extent), so you might want to copy the code there and see what you get: http://www.developerfusion.com/tools/convert/csharp-to-vb/.
Groo
A: 

Quick simple very slow but it works.

The idea is to copy the screen to a bitmap which can be done using the GDI+ build into the drawing.graphics object. Then simply read the bitmap that it generates. Get pixel is very slow. The best way it to read the image byte array directly.

Function MakeScreenShot() As Drawing.Bitmap
    Dim out As Drawing.Bitmap

    'Get the screen Size
    Dim bounds As Rectangle = Screen.GetBounds(Point.Empty)

    'create the bitmap
    out = New Drawing.Bitmap(bounds.Width, bounds.Height)

    'create a graphic object to recive the pic
    Using gr As Drawing.Graphics = Graphics.FromImage(out)
        'Copy the screen using built in API
        gr.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size)
    End Using

    Return out
End Function

Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
    Dim BM As Drawing.Bitmap = MakeScreenShot()
    Dim mouseloc As Point = Cursor.Position
    Dim c As Color = BM.GetPixel(mouseloc.X, mouseloc.Y) ' The Slowest way possable to read a color

    Debug.Print(c.R & "," & c.G & "," & c.B)
End Sub

Enjoy.

notstarman