Microsoft Docs

CreateDC function

Creates a device context (DC) for a device using the specified driver.

Syntax
Parameters
Return Value
Remarks
Example
HDC CreateDC(
    LPCTSTR   pwszDriver,
    LPCTSTR   pwszDevice,
    LPCTSTR   pwszOutput,
    const DEVMODE *pdevmode
);
ParameterTypeDescription
pwszDriverLPCTSTRName of the device driver (e.g., "DISPLAY").
pwszDeviceLPCTSTRDevice name; can be NULL for the default device.
pwszOutputLPCTSTRPort name (e.g., "COM1:"); can be NULL.
pdevmodeconst DEVMODE*Pointer to a DEVMODE structure that defines the device initialization parameters; can be NULL for defaults.

Returns a handle to the newly created device context. If the function fails, the return value is NULL. Call GetLastError for extended error information.

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

int main() {
    HDC hdc = CreateDC(L"DISPLAY", NULL, NULL, NULL);
    if (!hdc) {
        printf("CreateDC failed: %ld\n", GetLastError());
        return 1;
    }

    // Draw a simple rectangle
    RECT rc = {50, 50, 300, 200};
    FillRect(hdc, &rc, (HBRUSH)(COLOR_WINDOW+1));

    // Clean up
    DeleteDC(hdc);
    return 0;
}