Orel Oreliniow
Orel Oreliniow

Reputation: 71

C# get pixel color from another window

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.

Upvotes: 7

Views: 7770

Answers (1)

Arturo Menchaca
Arturo Menchaca

Reputation: 15982

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);

Upvotes: 5

Related Questions