我想从另一个窗口获取像素颜色。我的代码是:
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;
}
}
问题是这段代码正在扫描整个屏幕,这不是我想要的。想法是修改代码以基于另一个应用程序屏幕边界扫描像素颜色。也许是FindWindow或GetWindow的东西?提前谢谢。
答案 0 :(得分:1)
您可以按照标题导入FindWindow
来查找窗口:
[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);
}
然后,使用处理程序为您的GetPixelColor
添加一个额外的参数:
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;
}
用法:
var title = "windows caption";
var hwnd = FindWindowByCaption(title);
var pixel = Win32.GetPixelColor(hwnd, x, y);