How to correctly screencapture a specific window on Aero/DWM

后端 未结 2 1592
悲&欢浪女
悲&欢浪女 2021-02-03 15:35

Background info: I have this MFC application I coded and been using for a long time that pretty much automatically saves screenshots to the hard disk when the user hits the Prin

2条回答
  •  别那么骄傲
    2021-02-03 16:11

    It's an excellent question that I unfortuneatly don't know exact answer to. My first idea was to grab the whole desktop and cut interesting part out of it.

    I've dug into QT 4.5 sources to see how they do it, and found something like this. If you switch GetClientRect to GetWindowRect and strip QT boilerplate code you should get what you want. It looks like a hack though :)

    
    QPixmap QPixmap::grabWindow(WId winId, int x, int y, int w, int h )
    {
        RECT r;
        GetClientRect(winId, &r);  
        if (w < 0) w = r.right - r.left;
        if (h < 0) h = r.bottom - r.top;  
        // Create and setup bitmap
        HDC display_dc = GetDC(0);
        HDC bitmap_dc = CreateCompatibleDC(display_dc);
        HBITMAP bitmap = CreateCompatibleBitmap(display_dc, w, h);
        HGDIOBJ null_bitmap = SelectObject(bitmap_dc, bitmap);
    
        // copy data
        HDC window_dc = GetDC(winId);
        BitBlt(bitmap_dc, 0, 0, w, h, window_dc, x, y, SRCCOPY);
    
        // clean up all but bitmap
        ReleaseDC(winId, window_dc);
        SelectObject(bitmap_dc, null_bitmap);
        DeleteDC(bitmap_dc);
    
        QPixmap pixmap = QPixmap::fromWinHBITMAP(bitmap);
    
        DeleteObject(bitmap);
        ReleaseDC(0, display_dc);
    
        return pixmap;
    }
    

提交回复
热议问题