【问题标题】:Saving screenshot of a specific window as bmp in window将特定窗口的屏幕截图保存为窗口中的 bmp
【发布时间】:2014-06-26 14:20:57
【问题描述】:

我需要以.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;
}

但是我的函数获取整个屏幕的图像。我该如何解决这个问题?

【问题讨论】:

  • 您是否确认 MyHWND 确实是您需要捕获的窗口的句柄?您是否使用 Spy++ 或类似工具进行验证?
  • 如果窗口不在前景中,或者被另一个窗口部分覆盖,或者被最小化,则不能保证它会被吸引到您试图从中复制的 DC。
  • 好的,我想通了!

标签: c++ windows


【解决方案1】:

这是我从其他地方找到的解决方案:

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 是一个包含窗口名称或部分名称的全局变量。

【讨论】:

    猜你喜欢
    • 2012-07-02
    • 2017-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-30
    • 1970-01-01
    • 2019-09-15
    相关资源
    最近更新 更多