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
| Parameter | Description |
|---|---|
hWnd | Handle 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
- The retrieved DC must be released by calling ReleaseDC when you are finished using it.
- A
GetDCcall increments the DC's reference count. Each successfulGetDCmust be matched by a correspondingReleaseDC. - Do not store the returned DC for longer than the scope of your operation; retrieve a fresh DC each time you need one.
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;
}