- 1 year ago
Taking screenshot of window (handle) in C++
Comment
1 / 1
To take a screenshot of a specific window (handle) in C++, you can use the Windows API functions. Here's an example of how you can capture a screenshot of a window:
cpp#include <Windows.h>
#include <iostream>
void CaptureScreenshot(HWND windowHandle)
{
// Get the window dimensions
RECT windowRect;
GetClientRect(windowHandle, &windowRect);
// Create a bitmap with the window dimensions
HDC windowDC = GetDC(windowHandle);
HDC memoryDC = CreateCompatibleDC(windowDC);
HBITMAP bitmap = CreateCompatibleBitmap(windowDC, windowRect.right, windowRect.bottom);
SelectObject(memoryDC, bitmap);
// Copy the window content to the bitmap
PrintWindow(windowHandle, memoryDC, PW_CLIENTONLY);
// Save the bitmap to a file
BITMAP bmp;
GetObject(bitmap, sizeof(BITMAP), &bmp);
BITMAPFILEHEADER bmfHeader;
BITMAPINFOHEADER bi;
bi.biSize = sizeof(BITMAPINFOHEADER);
bi.biWidth = bmp.bmWidth;
bi.biHeight = bmp.bmHeight;
bi.biPlanes = 1;
bi.biBitCount = bmp.bmBitsPixel;
bi.biCompression = BI_RGB;
bi.biSizeImage = 0;
bi.biXPelsPerMeter = 0;
bi.biYPelsPerMeter = 0;
bi.biClrUsed = 0;
bi.biClrImportant = 0;
DWORD dwBmpSize = ((bmp.bmWidth * bi.biBitCount + 31) / 32) * 4 * bmp.bmHeight;
// Create the file header
bmfHeader.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
bmfHeader.bfSize = dwBmpSize + sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
bmfHeader.bfType = 0x4D42; // BM
// Create the file
HANDLE fileHandle = CreateFile("screenshot.bmp", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
// Write the file header and bitmap data to the file
DWORD dwBytesWritten;
WriteFile(fileHandle, (LPSTR)&bmfHeader, sizeof(BITMAPFILEHEADER), &dwBytesWritten, NULL);
WriteFile(fileHandle, (LPSTR)&bi, sizeof(BITMAPINFOHEADER), &dwBytesWritten, NULL);
WriteFile(fileHandle, (LPSTR)bmp.bmBits, dwBmpSize, &dwBytesWritten, NULL);
// Cleanup
CloseHandle(fileHandle);
DeleteObject(bitmap);
DeleteDC(memoryDC);
ReleaseDC(windowHandle, windowDC);
std::cout << "Screenshot saved to screenshot.bmp" << std::endl;
}
int main()
{
HWND targetWindow = FindWindow(nullptr, "Window Title"); // Replace "Window Title" with the actual window title
if (targetWindow != nullptr)
{
CaptureScreenshot(targetWindow);
}
else
{
std::cout << "Window not found!" << std::endl;
}
return 0;
}
In this example, replace "Window Title"
in the FindWindow
function with the title of the window for which you want to capture a screenshot.
The CaptureScreenshot
function takes the window handle as a parameter and performs the following steps:
- Retrieves the dimensions of the window using
GetClientRect
. - Creates a compatible bitmap and selects it into a memory device context (DC) using `