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

Posted 阿汤的博客

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 = 0, ScrHeight = 0; RECT rect = { 0 }; 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 = { 0 }; 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, 0, 0, ScrWidth, ScrHeight, hdc, rect.left, rect.top, SRCCOPY); GetDIBits(hmdc, hBmpScreen, 0L, (DWORD)ScrHeight, buf, (LPBITMAPINFO)&bi, (DWORD)DIB_RGB_COLORS); BITMAPFILEHEADER bfh = { 0 }; bfh.bfType = ((WORD)(\'M\' << 8) | \'B\'); bfh.bfSize = sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER)+bi.biSizeImage; bfh.bfOffBits = sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER); HANDLE hFile = CreateFile(filename, GENERIC_WRITE, 0, 0, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); 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[256] = {0}; for (int32_t i = 0; i < 20; ++i) { sprintf_s(name, 256, "%d.bmp", i); printf("shooting %s\\n", name); ShootScreen(name, NULL); Sleep(1000); } return 0; }

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

 

以上是关于C++ 在Windows下截取整个屏幕 和 指定句柄窗口的屏幕的主要内容,如果未能解决你的问题,请参考以下文章

.NET Windows 7 在使用“本地系统帐户”在“Windows 服务”下运行时截取屏幕截图不起作用

Mac下截图快捷键

Python攻防-截取屏幕并自动发送指定邮箱

Chrome 扩展程序截取的屏幕截图 - 隐私风险?

安卓开发截取当前屏幕图片及截取整个ListView图片并保存到本地

node-webkit 或 atom-shell 可以截取整个桌面屏幕吗?