有没有办法在不截取 C# 屏幕截图的情况下捕获屏幕像素的颜色?



我正在制作一个程序来检测屏幕的扇区以执行我需要的操作,我正在通过屏幕截图逐个像素地查看以找到我想要分析的扇区并与我想要的更改进行比较,但我有一个问题,我使用计时器每秒每 20 次截取一次屏幕截图,负责截取屏幕截图的句子以一个我完全不明白的异常,它有时工作正常,直到出现异常"ArgumentsException"和消息"参数无效",所以我不知道会发生什么,我应该发送正确的参数,我什至将句子设置为 null 认为遗漏了一些东西但没有, 同样的事情还在继续,我不明白为什么。

现在,我不知道是否有任何其他方法可以直接检测并且无需截取屏幕截图,因为我发现从屏幕捕获图像的句子存在问题。

我用来截图的代码是:

screenCapture = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppRgb);
g = Graphics.FromImage(screenCapture);
g.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, screenCapture.Size, CopyPixelOperation.SourceCopy);

有时问题出在位图上,有时是图形出现了同样的问题,所以你能推荐我达到我要求的目的吗?

无需截屏,即可使用 Win32 API GetPixel: https://www.pinvoke.net/default.aspx/gdi32/getpixel.html

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

或者考虑Blit,因为它们比屏幕截图便宜,C# - SetPixel和GetPixel的更快替代方案,用于Windows Forms应用程序的位图。

相关内容

最新更新