Windows API Reference Microsoft Docs

GetDC function

The GetDC function retrieves a handle to a device context (DC) for the client area of a specified window or for the entire screen.

Syntax

#include <windows.h>

HDC GetDC(
    HWND hWnd
);

Parameters

ParameterDescription
hWndHandle to the window whose DC is to be retrieved. If this parameter is NULL, GetDC returns the DC for the entire screen.

Return value

If the function succeeds, the return value is a handle to a device context for the specified window. If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Remarks

Example

#include <windows.h>
#include <stdio.h>

int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR lpCmd, int nShow)
{
    HWND hwnd = GetForegroundWindow(); // get the active window
    HDC hdc = GetDC(hwnd);
    if (!hdc) {
        MessageBox(NULL, L"Failed to get DC", L"Error", MB_ICONERROR);
        return 0;
    }

    // Draw a red rectangle in the client area
    HBRUSH hBrush = CreateSolidBrush(RGB(255,0,0));
    RECT rc;
    GetClientRect(hwnd, &rc);
    FillRect(hdc, &rc, hBrush);
    DeleteObject(hBrush);

    // Release the DC
    ReleaseDC(hwnd, hdc);
    return 0;
}

See also