본문 바로가기
코드/C++

pixel color fast

by bongin 2022. 7. 27.
728x90
반응형
https://stackoverflow.com/questions/10515646/get-pixel-color-fastest-way

Get Pixel color fastest way?
I'm trying to make an auto-cliker for an windows app. It works well, but it's incredibly slow! I'm currently using the method "getPix...
stackoverflow.com

I'm trying to make an auto-cliker for an windows app. It works well, but it's incredibly slow! I'm currently using the method "getPixel" which reloads an array everytime it's called.
Here is my current code:

hdc = GetDC(HWND_DESKTOP);
bx = GetSystemMetrics(SM_CXSCREEN);
by = GetSystemMetrics(SM_CYSCREEN);
start_bx = (bx/2) - (MAX_WIDTH/2);
start_by = (by/2) - (MAX_HEIGHT/2);
end_bx = (bx/2) + (MAX_WIDTH/2);
end_by = (by/2) + (MAX_HEIGHT/2);

for(y=start_by; y<end_by; y+=10)
{
	for(x=start_bx; x<end_bx; x+=10)
	{
		pixel = GetPixel(*hdc, x, y);
		if(pixel==RGB(255, 0, 0))
		{
			SetCursorPos(x,y);
			mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
			Sleep(50);
			mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
			Sleep(25);
		}
	}
}



I found a perfect way which is clearly faster than the GetPixel one:

HDC hdc, hdcTemp;
RECT rect;
BYTE* bitPointer;
int x, y;
int red, green, blue, alpha;

while(true)
{
	hdc = GetDC(HWND_DESKTOP);
	GetWindowRect(hWND_Desktop, &rect);
	int MAX_WIDTH = rect.right;
	int MAX_HEIGHT = rect.bottom;

	hdcTemp = CreateCompatibleDC(hdc);
	BITMAPINFO bitmap;
	bitmap.bmiHeader.biSize = sizeof(bitmap.bmiHeader);

	bitmap.bmiHeader.biWidth = MAX_WIDTH;
	bitmap.bmiHeader.biHeight = MAX_HEIGHT;
	bitmap.bmiHeader.biPlanes = 1;
	bitmap.bmiHeader.biBitCount = 32;
	bitmap.bmiHeader.biCompression = BI_RGB;
	bitmap.bmiHeader.biSizeImage = MAX_WIDTH * 4 * MAX_HEIGHT;
	bitmap.bmiHeader.biClrUsed = 0;
	bitmap.bmiHeader.biClrImportant = 0;

	HBITMAP hBitmap2 = CreateDIBSection(hdcTemp, &bitmap, DIB_RGB_COLORS, (void**)(&bitPointer), NULL, NULL);
	SelectObject(hdcTemp, hBitmap2);
	BitBlt(hdcTemp, 0, 0, MAX_WIDTH, MAX_HEIGHT, hdc, 0, 0, SRCCOPY);

	for (int i=0; i<(MAX_WIDTH * 4 * MAX_HEIGHT); i+=4)
	{
		red = (int)bitPointer[i];
		green = (int)bitPointer[i+1];
		blue = (int)bitPointer[i+2];
		alpha = (int)bitPointer[i+3];

		x = i / (4 * MAX_HEIGHT);
		y = i / (4 * MAX_WIDTH);

		if (red == 255 && green == 0 && blue == 0)
		{
			SetCursorPos(x,y);
			mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
			Sleep(50);
			mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
			Sleep(25);
		}
	}
}

I hope this could help someone else.
728x90
반응형

'코드 > C++' 카테고리의 다른 글

GetPixel  (0) 2022.07.27
참조 (Ampersand)  (0) 2022.07.27
함수 재정의와 함수 오버라이딩(virtual)  (0) 2022.07.27
section .bss  (0) 2022.07.27
CMD ASLR : 임의 기준 주소  (0) 2022.07.27

댓글