Create a device context (HDC) for the window you want to take a screenshot of using the GetDC function.
Create a compatible device context using the CreateCompatibleDC function.
Create a compatible bitmap using the CreateCompatibleBitmap function and the dimensions of the window.
Select the compatible bitmap into the compatible device context using the SelectObject function.
Use the BitBlt function to copy the contents of the window's device context to the compatible device context.
Unlock the compatible bitmap using the GetObject function.
Copy the bitmap data to a buffer using the GetDIBits function.
Release the device contexts and the bitmap.
Here's an example code snippet to take a screenshot of an app window and store it in memory:
HWND hwnd = ::GetDesktopWindow(); // change this to the handle of the window you want to take a screenshot of
// Get the dimension of the window
RECT rect;
::GetClientRect(hwnd, &rect);
int width = rect.right - rect.left;
int height = rect.bottom - rect.top;
// Create a device context for the window
HDC hdcSrc = ::GetDC(hwnd);
// Create a compatible device context
HDC hdcMem = ::CreateCompatibleDC(hdcSrc);
// Create a compatible bitmap
HBITMAP hBitmap = ::CreateCompatibleBitmap(hdcSrc, width, height);
// Select the bitmap into the compatible device context
HGDIOBJ hOld = ::SelectObject(hdcMem, hBitmap);
// Copy the contents of the window's device context to the compatible device context
::BitBlt(hdcMem, 0, 0, width, height, hdcSrc, 0, 0, SRCCOPY);
// Unlock the bitmap
BITMAP bm;
::GetObject(hBitmap, sizeof(BITMAP), &bm);
// Allocate memory for the bitmap data
DWORD dwSize = bm.bmWidthBytes * bm.bmHeight;
BYTE* lpBits = new BYTE[dwSize];
// Copy the bitmap data to the buffer
BITMAPINFOHEADER bih;
bih.biSize = sizeof(BITMAPINFOHEADER);
bih.biWidth = bm.bmWidth;
bih.biHeight = bm.bmHeight;
bih.biPlanes = 1;
bih.biBitCount = 24;
bih.biCompression = BI_RGB;
bih.biSizeImage = bm.bmWidthBytes * bm.bmHeight;
bih.biXPelsPerMeter = 0;
bih.biYPelsPerMeter = 0;
bih.biClrUsed = 0;
bih.biClrImportant = 0;
::GetDIBits(hdcMem, hBitmap, 0, bm.bmHeight, lpBits, (BITMAPINFO *)&bih, DIB_RGB_COLORS);
// Release the device contexts and the bitmap
delete[] lpBits;
::SelectObject(hdcMem, hOld);
::DeleteObject(hBitmap);
::DeleteDC(hdcMem);
::ReleaseDC(hwnd, hdcSrc);
The resulting screenshot data will be stored in the lpBits buffer.