如何获取光标下的像素颜色?

4
我需要一个快速的命令行应用程序来返回鼠标光标下像素的颜色。我该如何在VC++中构建这个应用程序?我需要类似于这个的东西,但最好不要使用.NET,以便可以每秒运行多次。
1个回答

15

就我所知,直接的方式是:

#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;
}

注: 看起来可以运行,至少对我而言如此。

注2: 添加了一些错误检查。

注3: 对代码进行了注释,编译了可执行文件,Visual Studio解决方案可以在我的 SVN 存储库中找到。


非常感谢!我想我应该在“Win32控制台应用程序”中构建它吧? - Robin Rodricks
@Jeremy:是的。我无法弄清如何从命令行构建它,但在Visual Studio中作为控制台应用程序运行良好。 - Joey
谢谢!还有一件事,我正在尝试从另一个应用程序中调用此后台进程,那么有没有办法隐藏黑色命令行窗口不显示? - Robin Rodricks
我在这里寻找一些答案.. https://dev59.com/73E85IYBdhLWcg3wdDSz .. 但你知道一个快速的方法来做同样的事情吗?我基本上需要返回一些值而不显示控制台窗口。 - Robin Rodricks
几乎每种语言/环境都有运行控制台程序并检索其输出的功能。使用适用于您的内容。我不知道您想从哪种编程语言中运行它。对于纯Windows API,您可以使用“CreateProcess”,在C#中使用“Process.Start”,在C中可以使用“popen”等。... - Joey

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接