首页 > 解决方案 > 在 MFC (C++) 中捕获并保存窗口的屏幕截图

问题描述

我想在 MFC 中捕获窗口的屏幕截图并将其保存为图像文件。按照这些例子,我得到了如下的东西

OnSave()
{
    CRect rect;
    GetWindowRect(&rect);
    CImage* img = new CImage();
    img->Create(rect.Width(), rect.Height(), 32);
    HDC device_context_handle = img->GetDC();
    HWND hwnd = this->GetSafeHwnd();
    bool IsPrint =::PrintWindow(hwnd, device_context_handle, PW_CLIENTONLY);
    HRESULT res = img->Save(L"image12.bmp", Gdiplus::ImageFormatBMP);
    img->ReleaseDC();

    delete img;
}

这样做,我得到了正确尺寸的文件,但它总是黑色的。我检查了结果保存(res)也始终为0。我尝试在线检查不同的示例,但无法修复此黑色图像问题。有没有建议修改这个或以不同的方式做这个?

标签: c++imagemfcgdi+atl

解决方案


像下面这样的事情应该这样做

    int x1, y1, x2, y2, w, h;

    // get window dimensions for following vars.
    // Don.t know if you want all area or just client area,
    // so use GetClientRect or GetWindowRect accordingly.
    // These functions sometimes are not so obvious on what they do.
    x1 = /**/;
    y1 = /**/;
    x2 = /**/;
    y2 = /**/;

    // width and height
    w = x2 - x1;
    h = y2 - y1;

    // copy window to bitmap
    HDC     hWindow = (HDC) window.GetDC();
    HDC     hDC = CreateCompatibleDC(hWindow);
    HBITMAP hBitmap = CreateCompatibleBitmap(hWindow, w, h);
    HGDIOBJ old_obj = SelectObject(hDC, hBitmap);
    BOOL    bRet = BitBlt(hDC, 0, 0, w, h, hWindow, x1, y1, SRCCOPY);
    
    CImage image;
    image.Attach(hBitmap);
    image.Save(debug_dir + L"window.bmp", Gdiplus::ImageFormatBMP);

    // clean-up
    SelectObject(hDC, old_obj);
    DeleteDC(hDC);
    ::ReleaseDC(NULL, hWindow);
    DeleteObject(hBitmap);

推荐阅读