Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,971 questions

51,913 answers

573 users

How to use the GetPixel function to get a pixel color using the Win32 API in C++

1 Answer

0 votes
#include <windows.h>
#include <string>

LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    switch (msg)
    {
        case WM_PAINT:
        {
            PAINTSTRUCT ps;
            HDC hdc = BeginPaint(hWnd, &ps);

            // Draw a red pixel
            SetPixel(hdc, 50, 50, RGB(255, 0, 0));

            // Read the pixel back
            COLORREF c = GetPixel(hdc, 50, 50);

            if (c != CLR_INVALID)
            {
                int r = GetRValue(c);
                int g = GetGValue(c);
                int b = GetBValue(c);

                // Build a window title string
                std::wstring title =
                    L"GetPixel Example - R=" + std::to_wstring(r) +
                    L" G=" + std::to_wstring(g) +
                    L" B=" + std::to_wstring(b);

                SetWindowText(hWnd, title.c_str()); // See on the window title
            }

            EndPaint(hWnd, &ps);
        }
        return 0;

        case WM_DESTROY:
            PostQuitMessage(0);
            return 0;
        }

    return DefWindowProc(hWnd, msg, wParam, lParam);
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE, LPSTR, int nCmdShow)
{
    const wchar_t CLASS_NAME[] = L"GetPixelDemo";

    WNDCLASS wc = {};
    wc.lpfnWndProc = WndProc;
    wc.hInstance = hInstance;
    wc.lpszClassName = CLASS_NAME;

    RegisterClass(&wc);

    HWND hWnd = CreateWindowEx(
        0,
        CLASS_NAME,
        L"GetPixel Example",
        WS_OVERLAPPEDWINDOW,
        CW_USEDEFAULT, CW_USEDEFAULT,
        640, 480,
        NULL,
        NULL,
        hInstance,
        NULL
    );

    ShowWindow(hWnd, nCmdShow);

    MSG msg = {};
    while (GetMessage(&msg, NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    return 0;
}




/*
run:

GetPixel Example - R=255 G=0 B=0

*/

 



answered 7 hours ago by avibootz
...