我需要以.bmp
格式获取特定窗口的屏幕视图。换句话说,我需要具有alt+printscreen
的功能,即使窗口处于后面或最小化,它也需要工作。所以我在下面编写了一个函数,它返回一个HBITMAP
类型,以便稍后将视图另存为.bmp
文件。
HBITMAP CaptureWindowBitmap(HWND MyHWND)
{
HDC hWindowDC = GetWindowDC(MyHWND);
HDC hMemoryDC = CreateCompatibleDC(hWindowDC);
int x = GetDeviceCaps(hWindowDC, HORZRES);
int y = GetDeviceCaps(hWindowDC, VERTRES);
HBITMAP hBitmap = CreateCompatibleBitmap(hWindowDC, x, y);
HBITMAP hBitmapOld = (HBITMAP)SelectObject(hMemoryDC, hBitmap);
BitBlt(hMemoryDC, 0, 0, x, y, hWindowDC, 0, 0, SRCCOPY);
hBitmap = (HBITMAP)SelectObject(hMemoryDC, hBitmapOld);
DeleteDC(hMemoryDC);
DeleteDC(hWindowDC);
return hBitmap;
}
然而,我的功能获取整个屏幕的图像。我该如何解决这个问题?
答案 0 :(得分:0)
以下是我从其他地方找到的解决方案:
HBITMAP CaptureWindowBitmap(HWND MyHWND)
{
RECT rc;
GetClientRect(MyHWND, &rc);
HDC hdcScreen = GetDC(NULL);
HDC hdc = CreateCompatibleDC(hdcScreen);
HBITMAP hbmp = CreateCompatibleBitmap(hdcScreen, rc.right - rc.left, rc.bottom - rc.top);
SelectObject(hdc, hbmp);
PrintWindow(MyHWND, hdc, PW_CLIENTONLY);
DeleteDC(hdc);
ReleaseDC(NULL, hdcScreen);
return hbmp;
}
窗口由以下函数捕获:
BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam)
{
char buffer[128];
int written = GetWindowTextA(hwnd, buffer, 128);
if (written && strstr(buffer,WindowName) ) {
*(HWND*)lParam = hwnd;
return FALSE;
}
return TRUE;
}
HWND GetHwnd()
{
HWND hWnd = NULL;
EnumWindows(EnumWindowsProc, (LPARAM)&hWnd);
return hWnd;
}
其中LPCTSTR WindowName
是一个包含窗口名称或部分名称的全局变量。