如何在C ++中将窗口的屏幕截图作为位图对象?

时间:2011-09-03 11:12:37

标签: c++ windows visual-c++ bitmap window

如何在C ++中将窗口的屏幕截图作为位图对象?假设我已经有了窗口句柄。 我还想知道当窗口处于最小化状态时是否可以获取窗口的屏幕截图

C ++这里的意思是VC ++,所有库都与Windows XP +(win32)相关联。

3 个答案:

答案 0 :(得分:23)

你应该调用PrintWindow API:

void CScreenShotDlg::OnPaint()
{
    // device context for painting
    CPaintDC dc(this);

    // Get the window handle of calculator application.
    HWND hWnd = ::FindWindow( 0, _T( "Calculator" ));

    // Take screenshot.
    PrintWindow( hWnd,
                 dc.GetSafeHdc(),
                 0 );
}

请参阅此问题:getting window screenshot windows API

如果你没有使用MFC,这里是纯PrintWindow签名:

BOOL PrintWindow(
    HWND hwnd,
    HDC hdcBlt,
    UINT nFlags
);

有关详细信息,请参阅MSDN:http://msdn.microsoft.com/en-us/library/dd162869(v=vs.85).aspx

关于如何将其保存为位图asMatteo所说取决于您使用的实际框架......

修改

这是原始C ++中的完整示例

#define _WIN32_WINNT    0x0501        //xp
#include <windows.h>

int main()
{ 
    RECT rc;
    HWND hwnd = FindWindow(TEXT("Notepad"), NULL);    //the window can't be min
    if (hwnd == NULL)
    {
        cout << "it can't find any 'note' window" << endl;
        return 0;
    }
    GetClientRect(hwnd, &rc);

    //create
    HDC hdcScreen = GetDC(NULL);
    HDC hdc = CreateCompatibleDC(hdcScreen);
    HBITMAP hbmp = CreateCompatibleBitmap(hdcScreen, 
        rc.right - rc.left, rc.bottom - rc.top);
    SelectObject(hdc, hbmp);

    //Print to memory hdc
    PrintWindow(hwnd, hdc, PW_CLIENTONLY);

    //copy to clipboard
    OpenClipboard(NULL);
    EmptyClipboard();
    SetClipboardData(CF_BITMAP, hbmp);
    CloseClipboard();

    //release
    DeleteDC(hdc);
    DeleteObject(hbmp);
    ReleaseDC(NULL, hdcScreen);

    cout << "success copy to clipboard, please paste it to the 'mspaint'" << endl;

    return 0;
}

答案 1 :(得分:6)

如果有人有兴趣获得最小化窗口的PrintWindow图片,那么您可以在这里获得想法,如何完成任务: http://www.codeproject.com/Articles/20651/Capturing-Minimized-Window-A-Kid-s-Trick

快乐的编码;)

答案 2 :(得分:2)

Looks like PrintWindow is working with frontbuffer. I tried to take an IE screenshot. Open new a link, and try to get the picture. It will show the picture from the previous link.