[C#] 픽셀서치 PixelSearch
화면상의 픽셀을 얻기 위해서 BitBlt로 (1,1) 크기의 픽셀을 먼저 얻어봅시다.
// ex ) GetColorAt(pos);
/* [DllImport("gdi32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]
public static extern int BitBlt(IntPtr hDC, int x, int y, int nWidth, int nHeight, IntPtr hSrcDC, int xSrc, int ySrc, int dwRop);
추가하셔야 bitblt사용가능
*/
using System.Drawing;
public Color GetColorAt(Point location)
{
Bitmap screenPixel = new Bitmap(1, 1, PixelFormat.Format32bppArgb);
using (Graphics gdest = Graphics.FromImage(screenPixel))
{
using (Graphics gsrc = Graphics.FromHwnd(IntPtr.Zero))
{
IntPtr hSrcDC = gsrc.GetHdc();
IntPtr hDC = gdest.GetHdc();
int retval = BitBlt(hDC, 0, 0, 1, 1, hSrcDC, location.X, location.Y, (int)CopyPixelOperation.SourceCopy);
gdest.ReleaseHdc();
gsrc.ReleaseHdc();
}
}
return screenPixel.GetPixel(0, 0);
}
한 픽셀의 색을 얻는것이 이제 가능해졌습니다.
픽셀서치는 단순히 구간을 정해 GetPixel을 여러번한거죠. 그러면 screenPixel의 크기를 늘리고 BitBlt 로 캡쳐할 구간을 늘리면 되겠네요.
using System.Drawing;
public bool PixelSearch(int left,int top,int right,int bottom,Color data)
{
int width = right - left;
int height = bottom - top;
Bitmap screenBitmap = new Bitmap(width,height, PixelFormat.Format32bppArgb);
using (Graphics gdest = Graphics.FromImage(screenBitmap))
{
using (Graphics gsrc = Graphics.FromHwnd(IntPtr.Zero))
{
IntPtr hSrcDC = gsrc.GetHdc();
IntPtr hDC = gdest.GetHdc();
int retval = BitBlt(hDC, 0, 0, width, height, hSrcDC, left, top, (int)CopyPixelOperation.SourceCopy);
gdest.ReleaseHdc();
gsrc.ReleaseHdc();
for(int i = 0; i < height; i++)
{
for(int j=0; j< width; j++)
{
Color c = screenBitmap.GetPixel(0, 0);
if (c == data)
return true;
}
}
}
}
return false;
}