我正在寻找在 c# 中捕获单个屏幕像素颜色的最快方法到目前为止,我正在使用带有 System.Threading.Timer 的 GDI+ 方法,该方法在它的回调中调用捕获函数,但我正在寻找最实现目标的最佳方式
我当前的代码像这样运行
System.Threading.Timer stTimer = new System.Threading.Timer(timerFired, null, 0, 1);
它调用包含此方法的函数
[DllImport("gdi32.dll")]
private static extern int BitBlt(IntPtr srchDC, int srcX, int srcY, int srcW, int srcH, IntPtr desthDC, int destX, int destY, int op);
[DllImport("user32.dll")]
static extern bool ReleaseDC(IntPtr hWnd, IntPtr hDC);
Bitmap screenPixel = new Bitmap(1, 1);
IntPtr hdcMem = CreateCompatibleDC(IntPtr.Zero);
using (Graphics gdest = Graphics.FromImage(screenPixel))
{
using (Graphics gsrc = Graphics.FromHwnd(appWindow))
{
int y = 540;
Point loc = new Point(xVal, y);
IntPtr hSrcDC = gsrc.GetHdc();
IntPtr hDC = gdest.GetHdc();
int retval = BitBlt(hDC, 0, 0, 1, 1, hSrcDC, loc.X, loc.Y, (int)CopyPixelOperation.SourceCopy);
gdest.ReleaseHdc();
gsrc.ReleaseHdc();
}
}
Color c = screenPixel.GetPixel(0, 0);
但我也想知道 GetPixel 方法是否......
[DllImport("gdi32.dll")]
static extern uint GetPixel(IntPtr hdc, int nXPos, int nYPos);
...在仅获取单个像素的颜色的情况下,实际上可能会更快
我也在考虑尝试
[DllImport("user32.dll")]
static extern IntPtr GetWindowDC(IntPtr hWnd);
IntPtr hDC = GetWindowDC(appWindow);
int retval = BitBlt(hDC, 0, 0, 1, 1, hSrcDC, loc.X, loc.Y, (int)CopyPixelOperation.SourceCopy);
甚至尝试
[DllImport("gdi32.dll")]
private static extern int BitBlt(IntPtr srchDC, int srcX, int srcY, int srcW, int srcH, IntPtr desthDC, int destX, int destY, int op);
[DllImport("gdi32.dll", SetLastError = true)]
static extern IntPtr CreateCompatibleDC(IntPtr hdc);
[DllImport("user32.dll")]
static extern IntPtr GetWindowDC(IntPtr hWnd);
IntPtr hDC = CreateCompatibleDC(GetWindowDC(appWindow));
int retval = BitBlt(hDC, 0, 0, 1, 1, hSrcDC, loc.X, loc.Y, (int)CopyPixelOperation.SourceCopy);
但我不完全确定如何在 C# 上下文中使用 CreateCompatibleDC 函数,或者此时它是否真的在做任何有用的事情......
只要解决方案与 C# 兼容并包含非常受欢迎的代码示例,我真的愿意接受任何关于优化的建议,包括 GDI+ 库之外的方法
另外,我不太关心计时器的优化,但如果您在这方面有优化,请随时分享