#define MICROSOFT_WINDOWS_WINBASE_H_DEFINE_INTERLOCKED_CPLUSPLUS_OVERLOADS 0
#include <windows.h>
int WINAPI WinMain(
_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPSTR lpCmdLine,
_In_ int nCmdShow)
{
// 获取主显示设备上下文
HDC hdcScreen = GetDC(NULL);
// 为屏幕截图创建一个兼容的设备上下文
HDC hdcCompatible = CreateCompatibleDC(hdcScreen);
// 获取主显示器的尺寸
int width = GetDeviceCaps(hdcScreen, HORZRES);
int height = GetDeviceCaps(hdcScreen, VERTRES);
// 为截图创建一个位图
HBITMAP hBitmap = CreateCompatibleBitmap(hdcScreen, width, height);
// 选择位图到兼容的设备上下文中
HGDIOBJ hOldBitmap = SelectObject(hdcCompatible, hBitmap);
// 将主显示器的内容复制到兼容的设备上下文中
BitBlt(hdcCompatible, 0, 0, width, height, hdcScreen, 0, 0, SRCCOPY);
// 将原始位图恢复到兼容的设备上下文中
SelectObject(hdcCompatible, hOldBitmap);
// 释放兼容的设备上下文
DeleteDC(hdcCompatible);
// 释放主显示设备上下文
ReleaseDC(NULL, hdcScreen);
// 将截图保存到文件中
HANDLE hFile = CreateFile(TEXT("screenshot.bmp"), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
BITMAPFILEHEADER bfh;
BITMAPINFOHEADER bih;
DWORD dwBytesWritten;
bfh.bfType = 0x4d42; // "BM"
bfh.bfSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + width * height * 4;
bfh.bfReserved1 = 0;
bfh.bfReserved2 = 0;
bfh.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
bih.biSize = sizeof(BITMAPINFOHEADER);
bih.biWidth = width;
bih.biHeight = height;
bih.biPlanes = 1;
bih.biBitCount = 32;
bih.biCompression = BI_RGB;
bih.biSizeImage = 0;
bih.biXPelsPerMeter = 0;
bih.biYPelsPerMeter = 0;
bih.biClrUsed = 0;
bih.biClrImportant = 0;
WriteFile(hFile, &bfh, sizeof(BITMAPFILEHEADER), &dwBytesWritten, NULL);
WriteFile(hFile, &bih, sizeof(BITMAPINFOHEADER), &dwBytesWritten, NULL);
unsigned char* pData = (unsigned char*)malloc(width * height * 4);
if (pData != NULL) {
GetBitmapBits(hBitmap, width * height * 4, pData);
WriteFile(hFile, pData, width * height * 4, &dwBytesWritten, NULL);
}
free(pData);
CloseHandle(hFile);
return 0;
}
标签:bih,bfh,height,width,截屏,简单,sizeof,NULL From: https://blog.51cto.com/u_1685766/6273661