C# get pixel color from another window

后端 未结 1 706
甜味超标
甜味超标 2021-01-13 12:56

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

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


 seale         


        
1条回答
  •  庸人自扰
    2021-01-13 13:07

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

    0 讨论(0)
提交回复
热议问题