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.
views:
895answers:
3
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:
- Get a bitmap of the desktop/window close to the cursor position
- Index into that bitmap with the cursor position and extract the pixel color
It sounds simple, but is not easy.
Frank Krueger
2009-11-01 17:37:27
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
2009-11-01 17:39:27
+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
2009-11-01 17:39:12
+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
2009-11-01 17:53:48
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
2009-11-19 04:00:19