#pragma comment(lib, "dwmapi.lib")
2、创建一个函数来执行屏幕截图并过滤掉指定窗口:
bool CaptureScreen(const wchar_t* filePath)
// 获取屏幕大小
int screenWidth = GetSystemMetrics(SM_CXSCREEN);
int screenHeight = GetSystemMetrics(SM_CYSCREEN);
// 创建设备上下文
HDC screenDC = GetDC(NULL);
HDC memDC = CreateCompatibleDC(screenDC);
HBITMAP memBitmap = CreateCompatibleBitmap(screenDC, screenWidth, screenHeight);
HBITMAP oldBitmap = (HBITMAP)SelectObject(memDC, memBitmap);
// 使用DWM截取屏幕
HRESULT result = S_OK;
result = DwmGetDxSharedSurface(memDC, &memBitmap);
// 保存截图到文件
result = SaveBitmapToFile(memBitmap, filePath);
// 清理资源
SelectObject(memDC, oldBitmap);
DeleteObject(memBitmap);
DeleteDC(memDC);
ReleaseDC(NULL, screenDC);
return (result == S_OK);
3、创建一个函数来保存位图到文件:
HRESULT SaveBitmapToFile(HBITMAP bitmap, const wchar_t* filePath)
HRESULT result = S_OK;
// 创建位图信息头
BITMAP bmp;
GetObject(bitmap, sizeof(BITMAP), &bmp);
// 创建位图文件头
BITMAPFILEHEADER fileHeader;
fileHeader.bfType = 0x4D42; // "BM"
fileHeader.bfSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + bmp.bmWidthBytes * bmp.bmHeight;
fileHeader.bfReserved1 = 0;
fileHeader.bfReserved2 = 0;
fileHeader.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
// 创建位图信息头
BITMAPINFOHEADER infoHeader;
infoHeader.biSize = sizeof(BITMAPINFOHEADER);
infoHeader.biWidth = bmp.bmWidth;
infoHeader.biHeight = bmp.bmHeight;
infoHeader.biPlanes = 1;
infoHeader.biBitCount = bmp.bmBitsPixel;
infoHeader.biCompression = BI_RGB;
infoHeader.biSizeImage = 0;
infoHeader.biXPelsPerMeter = 0;
infoHeader.biYPelsPerMeter = 0;
infoHeader.biClrUsed = 0;
infoHeader.biClrImportant = 0;
// 创建文件并写入位图数据
HANDLE fileHandle = CreateFileW(filePath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (fileHandle != INVALID_HANDLE_VALUE)
DWORD bytesWritten = 0;
WriteFile(fileHandle, &fileHeader, sizeof(BITMAPFILEHEADER), &bytesWritten, NULL);
WriteFile(fileHandle, &infoHeader, sizeof(BITMAPINFOHEADER), &bytesWritten, NULL);
WriteFile(fileHandle, bmp.bmBits, bmp.bmWidthBytes * bmp.bmHeight, &bytesWritten, NULL);
CloseHandle(fileHandle);
result = E_FAIL;
return result;
4、调用CaptureScreen函数来进行屏幕截图:
int main()
const wchar_t* filePath = L"C:\\screenshot.bmp";
if (CaptureScreen(filePath, excludeWindow))
// 截图成功
// 截图失败
return 0;