4

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?

Community
  • 1
  • 1
Robin Rodricks
  • 110,798
  • 141
  • 398
  • 607

1 Answers1

15

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.

Joey
  • 344,408
  • 85
  • 689
  • 683
  • Thank you so much! I suppose I build this in a "Win32 Console App"?? – Robin Rodricks Jun 20 '10 at 11:01
  • @Jeremy: Yes. I couldn't figure out how to build it from the command line but as a console application from Visual Studio it worked fine. – Joey Jun 20 '10 at 11:06
  • Thanks! Just one more thing, I'm trying to invoke this behind-the-scenes from another App, so is there a way to hide the black commandline window from showing? – Robin Rodricks Jun 20 '10 at 11:58
  • I'm finding some answers here .. http://stackoverflow.com/questions/2763669/how-to-hide-a-console-application-in-c .. but do you know a quick way to do the same? I basically need to return some values without showing the console window. – Robin Rodricks Jun 20 '10 at 12:00
  • Pretty much every language/environment has a facility of running a console program and retrieving its output. Use what's applicable for you. I have no idea what programming language you want to run it from. For plain Windows API you can use `CreateProcess`, in C# use `Process.Start`, in C you can use `popen`, &c. ... – Joey Jun 20 '10 at 12:55