C#屏幕截图-颜色检入窗口,而不是全屏
我目前有一个c#代码,它从特定位置(光标位置)获取颜色。它工作得很好,但它的工作方式是,它需要全屏的“截图”,而不仅仅是特定的窗口。因此,如果在我监视的窗口上方有其他窗口,我会得到错误的颜色代码。有没有简单的方法来修改它,只检查特定窗口的“屏幕截图”,而不是全屏?这是C#屏幕截图-颜色检入窗口,而不是全屏,c#,screenshot,C#,Screenshot,我目前有一个c#代码,它从特定位置(光标位置)获取颜色。它工作得很好,但它的工作方式是,它需要全屏的“截图”,而不仅仅是特定的窗口。因此,如果在我监视的窗口上方有其他窗口,我会得到错误的颜色代码。有没有简单的方法来修改它,只检查特定窗口的“屏幕截图”,而不是全屏?这是 namespace MyApp { using System; using System.Drawing; using System.Windows.Forms; internal class S
namespace MyApp
{
using System;
using System.Drawing;
using System.Windows.Forms;
internal class Screeny
{
private IntPtr window;
public Bitmap CaptureFromScreen(Rectangle rect)
{
Bitmap image = !(rect == Rectangle.Empty) ? new Bitmap(rect.Width, rect.Height) : new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
Graphics graphics = Graphics.FromImage(image);
if (rect == Rectangle.Empty)
{
graphics.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, image.Size, CopyPixelOperation.SourceCopy);
return image;
}
graphics.CopyFromScreen(rect.X, rect.Y, 0, 0, rect.Size, CopyPixelOperation.SourceCopy);
return image;
}
public bool ExpectColor(Point p, string rgb)
{
Color colorFromScreen = this.GetColorFromScreen(p);
string[] strArray = rgb.Split(new char[] { '.' });
return (((colorFromScreen.R.ToString() == strArray[0]) && (colorFromScreen.G.ToString() == strArray[1])) && (colorFromScreen.B.ToString() == strArray[2]));
}
public Color GetColorFromScreen(Point p)
{
Bitmap bitmap = this.CaptureFromScreen(new Rectangle(p, new Size(2, 2)));
Color pixel = bitmap.GetPixel(0, 0);
bitmap.Dispose();
return pixel;
}
public void setWindow(IntPtr window)
{
this.window = window;
}
}
}
您需要获取要捕获的窗口
Rect
。要完成此任务,您需要一个结构
Rect
和一个可以获取窗口Rect
的方法:
[StructLayout(LayoutKind.Sequential)]
公共结构矩形
{
公共int左;
公共int top;
公共权利;
公共int底部;
}
[DllImport(“user32.dll”)]
公共静态外部IntPtr GetWindowRect(IntPtr hWnd,ref Rect Rect);
接下来,使用它:
公共静态位图GetWindowScreenshotOfProcess(进程)
{
var rect=new rect();
GetWindowRect(process.MainWindowHandle,ref rect);//填充rect对象
int width=rect.right-rect.left;
int height=rect.bottom-rect.top;
如果(宽度问题不是关于裁剪位图“…如果我在监视的窗口上方有其他窗口…”我想托管代码不行,您必须使用WinAPI。这里有一些很好的建议