7

I want to get a pixel color from another window. The code I have is:

using System;
using System.Drawing;
using System.Runtime.InteropServices;

sealed class Win32
{
    [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.Zero);
        uint pixel = GetPixel(hdc, x, y);
        ReleaseDC(IntPtr.Zero, hdc);
        Color color = Color.FromArgb((int)(pixel & 0x000000FF),
            (int)(pixel & 0x0000FF00) >> 8,
            (int)(pixel & 0x00FF0000) >> 16);
        return color;
    }
}

The problem is that this code is scanning the whole screen which is not what I want. The idea is to modify the code to scan for pixel color based on another application screen boundaries. Maybe something with FindWindow or GetWindow? Thanks in advance.

Ian H.
  • 3,840
  • 4
  • 30
  • 60

1 Answers1

5

You can import FindWindow as you said to find windows by the caption:

[DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
static extern IntPtr FindWindowByCaption(IntPtr ZeroOnly, string lpWindowName);

static IntPtr FindWindowByCaption(string caption)
{
    return FindWindowByCaption(IntPtr.Zero, caption);
}

Then, add an extra param to your GetPixelColor with the handler:

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

Usage:

var title = "windows caption";

var hwnd = FindWindowByCaption(title);

var pixel = Win32.GetPixelColor(hwnd, x, y);
Arturo Menchaca
  • 15,783
  • 1
  • 29
  • 53
  • 1
    The big problem with this (for anyone who wants to scan the whole screen, not the OP) is it's inefficient with the many P/Invoke calls. If you're using it for more than a few pixels it is going to be too slow. You could pipe the entire image to a Bitmap object and then access the scan0 pointer for faster speed. https://stackoverflow.com/a/911225/881111 – marknuzz Jul 19 '18 at 19:49
  • Offtopic, but further reading on why GetPixel this is slow, including interesting alternatives in the comments: https://devblogs.microsoft.com/oldnewthing/20211223-00/?p=106050 – Ray Jan 03 '22 at 14:22