I'm currently reading a certain pixels color from a process window like this:
[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);
}
It seems to be working.
I would like to know if I'm disposing everything that I use correctly to avoid memory leaks. If I inspect my app in the task manager I notice that the memory use is increasing a bit for each time i fetch a pixel, but I suppose the garbage collector will kick in when it's supposed to?
Also, is there any obvious "better" way of doing this?
Bitmap
. \$\endgroup\$