Get Pixel color fastest way?

前端 未结 2 758
离开以前
离开以前 2020-12-08 06:14

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 everytim

相关标签:
2条回答
  • 2020-12-08 06:20

    The simple answer is that if this is the method you insist on using then there isn't much to optimize. As others have pointed out in comments, you should probably use a different method for locating the area to click. Have a look at using FindWindow, for example.

    If you don't want to change your method, then at least sleep your thread for a bit after each complete screen scan.

    0 讨论(0)
  • 2020-12-08 06:45

    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.

    0 讨论(0)
提交回复
热议问题