1

How to get pixel color from another programming by handle?? what wrong with my code?

    [DllImport("user32.dll")]
    static extern IntPtr GetDC(IntPtr hwnd);

    [DllImport("user32.dll")]
    static extern Int32 ReleaseDC(IntPtr hwnd, IntPtr hdc);

    [DllImport("gdi32.dll")]
    static extern uint GetPixel(IntPtr hdc, int nXPos, int nYPos);

    static public System.Drawing.Color GetPixelColor(int x, int y)
    {
        IntPtr hdc = GetDC((IntPtr)2890812);
        uint pixel = GetPixel(hdc, x, y);
        ReleaseDC(IntPtr.Zero, hdc);
        System.Drawing.Color color = System.Drawing.Color.FromArgb((int)(pixel & 0x000000FF),
                     (int)(pixel & 0x0000FF00) >> 8,
                     (int)(pixel & 0x00FF0000) >> 16);
        return color;
    }

Returning is white color always.

2890812 is decimal Handle of another program from Spy++.

KPTH
  • 91
  • 1
  • 2
  • 12
  • what is it returning, and what do you expect it to return? – Cee McSharpface Sep 20 '17 at 19:05
  • R , G , B is 255 always – KPTH Sep 20 '17 at 19:06
  • 1
    that could indicate that the `COLORREF` which `pixel` holds, equals CLR_INVALID (0xFFFFFFFF) meaning the pixel is outside of the current clipping region. according to [docs](https://msdn.microsoft.com/de-de/library/windows/desktop/dd144909(v=vs.85).aspx). are you mixing up absolute screen coordinates with hDC relative coordinates? – Cee McSharpface Sep 20 '17 at 19:08
  • I don't know how to do that.Can you show me some example? – KPTH Sep 20 '17 at 19:11
  • pick different values for x and y. I cannot tell you which without knowing the calling code and the runtime situation on your screen(s). Or pass `null` to `GetDC` to get a handle for the entire screen. Which application/window/control are you targeting? the documentation has this to add: "A bitmap must be selected within the device context, otherwise, CLR_INVALID is returned on all pixels". – Cee McSharpface Sep 20 '17 at 19:18
  • I want to get pixel color when another program is minimize or not showing on my screen. Am i use correctly solution? – KPTH Sep 20 '17 at 19:29
  • please add this information to your question. and no, when it is minimized it must be forced to draw itself somewhere. some links to get you started: https://stackoverflow.com/q/830359/1132334, https://stackoverflow.com/a/17486560/1132334 – Cee McSharpface Sep 20 '17 at 19:32
  • @dlatikay thank you very much i think that can solve my problem!! – KPTH Sep 20 '17 at 19:37

0 Answers0