Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the pixel color under the cursor?

I need a fast command line app to return the color of the pixel under the mouse cursor.

How can I build this in VC++, I need something similar to this, but ideally not in .NET so it can be run many times per second?

like image 206
Robin Rodricks Avatar asked Dec 08 '22 02:12

Robin Rodricks


1 Answers

Off the top of my head, the straightforward way:

#include <stdio.h>
#include <Windows.h>

int main(void) {
    POINT p;
    COLORREF color;
    HDC hDC;
    BOOL b;

    // Get the device context for the screen
    hDC = GetDC(NULL);
    if (hDC == NULL)
        return 3;

    // Get the current cursor position
    b = GetCursorPos(&p);
    if (!b)
        return 2;

    // Retrieve the color at that position
    color = GetPixel(hDC, p.x, p.y);
    if (color == CLR_INVALID)
        return 1;

    // Release the device context again
    ReleaseDC(GetDesktopWindow(), hDC);

    printf("%i %i %i", GetRValue(color), GetGValue(color), GetBValue(color));
    return 0;
}

ETA: Appears to work, at least for me.

ETA2: Added some error checking

ETA3: Commented code, compiled executable and a Visual Studio Solution can be found in my SVN repository.

like image 193
Joey Avatar answered Dec 31 '22 14:12

Joey