HWND hwnd ; // 获取窗口句柄 hwnd = windows.at(ui->spinBox->value());使用hwnd截图
时间: 2024-03-13 07:42:40 浏览: 84
获取window句柄的小工具
3星 · 编辑精心推荐
了解了您的问题,您是想通过获取窗口的句柄来实现截屏功能。在 Windows 平台上,可以使用以下方式来实现:
```c++
#include <Windows.h>
bool CaptureScreen(HWND hWnd, const char* filename) {
HDC hDc = GetDC(hWnd);
HDC hMemDc = CreateCompatibleDC(hDc);
RECT rcClient;
GetClientRect(hWnd, &rcClient);
int nWidth = rcClient.right - rcClient.left;
int nHeight = rcClient.bottom - rcClient.top;
HBITMAP hBitmap = CreateCompatibleBitmap(hDc, nWidth, nHeight);
HBITMAP hOldBitmap = (HBITMAP)SelectObject(hMemDc, hBitmap);
BitBlt(hMemDc, 0, 0, nWidth, nHeight, hDc, 0, 0, SRCCOPY);
SelectObject(hMemDc, hOldBitmap);
DeleteDC(hMemDc);
ReleaseDC(hWnd, hDc);
PBITMAPINFO pbi;
pbi = CreateBitmapInfoStruct(hWnd, hBitmap);
LPBYTE lpBits;
lpBits = (LPBYTE)GlobalAlloc(GMEM_FIXED, pbi->bmiHeader.biSizeImage);
GetDIBits(hMemDc, hBitmap, 0, (UINT)pbi->bmiHeader.biHeight, lpBits, pbi, DIB_RGB_COLORS);
HANDLE hf;
BITMAPFILEHEADER hdr;
PBITMAPINFOHEADER pbih;
LPBYTE lpData;
DWORD dwTotal;
DWORD cb;
BYTE* hp;
DWORD dwTmp;
pbih = (PBITMAPINFOHEADER)pbi;
lpData = (LPBYTE)(lpBits + pbih->biSize + pbi->bmiHeader.biClrUsed * sizeof(RGBQUAD));
dwTotal = ((DWORD)(pbih->biSizeImage + sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER)));
hdr.bfType = 0x4d42;
hdr.bfSize = dwTotal;
hdr.bfReserved1 = 0;
hdr.bfReserved2 = 0;
hdr.bfOffBits = (DWORD)sizeof(BITMAPFILEHEADER) + (DWORD)sizeof(BITMAPINFOHEADER) + pbi->bmiHeader.biClrUsed * sizeof(RGBQUAD);
hf = CreateFile(filename, GENERIC_READ | GENERIC_WRITE, (DWORD)0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, (HANDLE)NULL);
if (hf == INVALID_HANDLE_VALUE) return false;
WriteFile(hf, (LPVOID)&hdr, sizeof(BITMAPFILEHEADER), (LPDWORD)&dwTmp, NULL);
WriteFile(hf, (LPVOID)pbih, sizeof(BITMAPINFOHEADER) + pbi->bmiHeader.biClrUsed * sizeof(RGBQUAD), (LPDWORD)&dwTmp, (NULL));
WriteFile(hf, (LPVOID)lpData, (DWORD)pbih->biSizeImage, (LPDWORD)&dwTmp, NULL);
CloseHandle(hf);
GlobalFree((HGLOBAL)lpBits);
DeleteObject(hBitmap);
return true;
}
```
上面的代码中,`CaptureScreen` 函数接收两个参数:`hWnd` 表示窗口句柄,`filename` 表示截图保存的文件名。该函数实现了从指定窗口截图,并将截图保存到指定文件中的功能。
注:上述代码中使用了一些辅助函数,如 `CreateBitmapInfoStruct`,请根据实际情况进行实现。
阅读全文