C# get pixel color from another window

我是研究僧i 提交于 2019-12-07 17:26:47

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/37056321/c-sharp-get-pixel-color-from-another-window

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!