参考:https://blog.csdn.net/sunflover454/article/details/48717731
参考:https://www.cnblogs.com/cdh49/p/3558353.html
在两篇文章基础上有修改,建立MFC工程,代码直接可用
void screenShot() {
//判断是不是窗口句柄如果是的话不能使用GetDC来获取DC 不然截图会是黑屏
HWND hwnd = ::GetDesktopWindow();
HDC pDC = CreateDCA("DISPLAY", NULL, NULL, NULL);
int BitPerPixel = ::GetDeviceCaps(pDC, BITSPIXEL);//获得颜色模式
int left = 0, top = 0; // 截屏左上角起点
int width = ::GetDeviceCaps(pDC, HORZRES); //设置图像宽度全屏
int height = ::GetDeviceCaps(pDC, VERTRES); //设置图像高度全屏
HDC memDC;//内存DC
memDC = ::CreateCompatibleDC(pDC);
HBITMAP memBitmap, oldmemBitmap;//建立和屏幕兼容的bitmap
memBitmap = ::CreateCompatibleBitmap(pDC, width, height);
oldmemBitmap = (HBITMAP)::SelectObject(memDC, memBitmap);//将memBitmap选入内存DC
if (hwnd == ::GetDesktopWindow()) {
BitBlt(memDC, 0, 0, width, height, pDC, left, top, SRCCOPY);//图像宽度高度和截取位置
} else {
bool bret = ::PrintWindow(hwnd, memDC, PW_CLIENTONLY);
if (!bret) {
BitBlt(memDC, 0, 0, width, height, pDC, left, top, SRCCOPY);//图像宽度高度和截取位置
}
}
//以下代码保存memDC中的位图到文件
BITMAP bmp;
::GetObject(memBitmap, sizeof(BITMAP), &bmp);;//获得位图信息
BITMAPINFOHEADER bih = { 0 };//位图信息头
bih.biBitCount = bmp.bmBitsPixel;//每个像素字节大小
bih.biCompression = BI_RGB;
bih.biHeight = bmp.bmHeight;//高度
bih.biPlanes = 1;
bih.biSize = sizeof(BITMAPINFOHEADER);
bih.biSizeImage = bmp.bmWidthBytes * bmp.bmHeight;//图像数据大小
bih.biWidth = bmp.bmWidth;//宽度
BITMAPFILEHEADER bfh = { 0 };//位图文件头
bfh.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);//到位图数据的偏移量
bfh.bfSize = bfh.bfOffBits + bmp.bmWidthBytes * bmp.bmHeight;//文件总的大小
bfh.bfType = (WORD)0x4d42;
DWORD dwBmpSize = ((bmp.bmWidth * bmp.bmBitsPixel + 31) / 32) * 4 * bmp.bmHeight;
char* allData = new char[dwBmpSize + sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER)];
ZeroMemory(allData, dwBmpSize + sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER));
memcpy(allData, (void*)&bfh, sizeof(BITMAPFILEHEADER));//写入位图文件头
memcpy(allData + sizeof(BITMAPFILEHEADER), (void*)&bih, sizeof(BITMAPINFOHEADER));//写入位图信息头
byte* p = new byte[bmp.bmWidthBytes * bmp.bmHeight];//申请内存保存位图数据
GetDIBits(memDC, (HBITMAP)memBitmap, 0, height, p, (LPBITMAPINFO)&bih, DIB_RGB_COLORS);//获取位图数据
memcpy(allData + sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER), p, dwBmpSize);
//FILE* fp;
//fopen_s(&fp, "H:\\1.bmp", "w+b");//图片保存路径和方式
//fwrite(allData, 1, dwBmpSize + sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER), fp);
//fclose(fp);
delete[] p;
delete[] allData;
DeleteObject(memBitmap);
DeleteDC(memDC);
ReleaseDC(hwnd, pDC);
}