我正在从流程窗口中读取某个像素颜色,如下所示:
[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);
public static Color GetPixel(IntPtr hwnd, int x, int y)
{
var screenPixel = new Bitmap(1, 1);
using (Graphics gdest = Graphics.FromImage(screenPixel))
{
using (Graphics gsrc = Graphics.FromHwnd(
MemoryHandler.GetMainWindowHandle()))
{
IntPtr hsrcdc = gsrc.GetHdc();
IntPtr hdc = gdest.GetHdc();
BitBlt(hdc, 0, 0, 1, 1, hsrcdc, x, y,
(int)CopyPixelOperation.SourceCopy);
gdest.ReleaseHdc();
gsrc.ReleaseHdc();
}
}
return screenPixel.GetPixel(0, 0);
}
[DllImport("gdi32.dll")]
static extern COLORREF GetPixel(IntPtr hdc, int nXPos, int nYPos);
[StructLayout(LayoutKind.Sequential)]
public struct COLORREF
{
public uint ColorDWORD;
public COLORREF(System.Drawing.Color color)
{
ColorDWORD = (uint)color.R + (((uint)color.G) << 8) +
(((uint)color.B) << 16);
}
public System.Drawing.Color GetColor()
{
return System.Drawing.Color.FromArgb((int)(0x000000FFU & ColorDWORD),
(int)(0x0000FF00U & ColorDWORD) >> 8, (int)(0x00FF0000U & ColorDWORD) >> 16);
}
public void SetColor(System.Drawing.Color color)
{
ColorDWORD = (uint)color.R + (((uint)color.G) << 8)
+ (((uint)color.B) << 16);
}
}
似乎工作正常。
我想知道我是否正在处理我正确使用的所有内容以避免内存泄漏。如果我在任务管理器中检查我的应用程序,我注意到每次获取像素时内存使用量都会增加一点,但我想垃圾收集器会在它应该启动时启动?
此外,有没有明显的“更好”的方法呢?