How to get screenshot of a window as bitmap object in C++?

you should call the 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 );
}

see this question: getting window screenshot windows API

if you are not using MFC, here the pure PrintWindow signature:

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

see MSDN for more details: http://msdn.microsoft.com/en-us/library/dd162869(v=vs.85).aspx

about how to save it as bitmap asMatteo said depends on the actual framework you are using…

EDIT:

here full example in raw 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;
}

Leave a Comment