How do I write a color picker (eye dropper) like Photoshop?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I would really like somethign where I can get the RGB value of whatever my
mouse is currently pointing at on the screen.

How is this accomplished via C#?
 
Ok I finally found a C# code snippet that tries to do this, but it is
resulting in an Exception.

The exmaple is here: http://www.bobpowell.net/eyedropper.htm

and the problem I get is on the line where it calls: "ReleaseDC(dc);"

error states:

"A call to PInvoke function 'ColorEditor!ColorEditor.Form1::ReleaseDC' has
unbalanced the stack. This is likely because the managed PInvoke signature
does not match the unmanaged target signature. Check that the calling
convention and parameters of the PInvoke signature match the target unmanaged
signature."

I am totally unfamiliar with interop calls, how do I fix this? How do I
investigate what the method signature looks like?
 
Ok, found out that the function signature was indeed incorrect on that web
site example, and I am now doing this:

[DllImport("user32.dll", EntryPoint = "GetDesktopWindow")]
public static extern IntPtr GetDesktopWindow();

[DllImport("user32.dll", EntryPoint = "GetDC")]
public static extern IntPtr GetDC(IntPtr ptr);

[DllImport("user32.dll", EntryPoint = "ReleaseDC")]
public static extern IntPtr ReleaseDC(IntPtr hWnd, IntPtr hDc);

and this is the relevant code for getting color at mouse position:

Point p = Control.MousePosition;
IntPtr dc = GetDC(GetDesktopWindow());

Color c = ColorTranslator.FromWin32(GetPixel(dc, p.X, p.Y));
panel.BackColor = c;
panel.Refresh();

ReleaseDC(GetDesktopWindow(), dc);

now it doesn't throw an exception but the problem now is that GetPixel
function seems to always be returning White, no matter what I mouse over. I
can confirm it's getting a correct mouse position and it's moving, and I am
mousing ove rimages which contain almost no white at all.
 
LoL OK it finally works.

Instead of getting an actual reference from GetDesktopWindow() function I
just use a "null pointer" aka IntPtr.Zero. works like a charm now!!
 
Back
Top