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

前端 未结 3 1203
被撕碎了的回忆
被撕碎了的回忆 2020-11-27 15:33

How to get screenshot of a window as bitmap object in C++? Supposed that I already have the window handle. And I want to know also whether it\'s possible to get the

3条回答
  •  有刺的猬
    2020-11-27 16:11

    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 
    
    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;
    }
    

提交回复
热议问题