C++ 在Windows下截取整个屏幕 和 指定句柄窗口的屏幕

#include <windows.h>
#include <stdint.h>
#include <stdio.h> void ShootScreen(const char* filename, HWND hWnd)
{
HDC hdc = CreateDC("DISPLAY", NULL, NULL, NULL);
int32_t ScrWidth = , ScrHeight = ;
RECT rect = { };
if (hWnd == NULL)
{
ScrWidth = GetDeviceCaps(hdc, HORZRES);
ScrHeight = GetDeviceCaps(hdc, VERTRES);
}
else
{
GetWindowRect(hWnd, &rect);
ScrWidth = rect.right - rect.left;
ScrHeight = rect.bottom - rect.top;
}
HDC hmdc = CreateCompatibleDC(hdc); HBITMAP hBmpScreen = CreateCompatibleBitmap(hdc, ScrWidth, ScrHeight);
HBITMAP holdbmp = (HBITMAP)SelectObject(hmdc, hBmpScreen); BITMAP bm;
GetObject(hBmpScreen, sizeof(bm), &bm); BITMAPINFOHEADER bi = { };
bi.biSize = sizeof(BITMAPINFOHEADER);
bi.biWidth = bm.bmWidth;
bi.biHeight = bm.bmHeight;
bi.biPlanes = bm.bmPlanes;
bi.biBitCount = bm.bmBitsPixel;
bi.biCompression = BI_RGB;
bi.biSizeImage = bm.bmHeight * bm.bmWidthBytes;
  // 图片的像素数据
char *buf = new char[bi.biSizeImage];
BitBlt(hmdc, , , ScrWidth, ScrHeight, hdc, rect.left, rect.top, SRCCOPY);
GetDIBits(hmdc, hBmpScreen, 0L, (DWORD)ScrHeight, buf, (LPBITMAPINFO)&bi, (DWORD)DIB_RGB_COLORS); BITMAPFILEHEADER bfh = { };
bfh.bfType = ((WORD)('M' << ) | 'B');
bfh.bfSize = sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER)+bi.biSizeImage;
bfh.bfOffBits = sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER);
HANDLE hFile = CreateFile(filename, GENERIC_WRITE, , , OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, );
DWORD dwWrite;
WriteFile(hFile, &bfh, sizeof(BITMAPFILEHEADER), &dwWrite, NULL);
WriteFile(hFile, &bi, sizeof(BITMAPINFOHEADER), &dwWrite, NULL);
WriteFile(hFile, buf, bi.biSizeImage, &dwWrite, NULL);
CloseHandle(hFile);
hBmpScreen = (HBITMAP)SelectObject(hmdc, holdbmp);
} int32_t main()
{
char name[] = {};
for (int32_t i = ; i < ; ++i)
{
sprintf_s(name, , "%d.bmp", i);
printf("shooting %s\n", name);
ShootScreen(name, NULL);
Sleep();
}
return ;
}

C++ 在Windows下截取整个屏幕  和 指定句柄窗口的屏幕

参考文章:http://blog.csdn.net/dazhong159/article/details/7909964

上一篇:rsync(三)算法原理和工作流程分析


下一篇:rsync算法原理和工作流程分析