如何为无框透明qt窗口截取屏幕截图?

时间:2018-04-28 01:43:43

标签: qt winapi gdi

Qt Window设置窗口标志和属性:

setWindowFlag(Qt::FramelessWindowHint);
setAttribute(Qt::WA_TranslucentBackground);

截图代码:

HDC hdc = GetDC(hwnd);
if (!hdc)
{
    LOGE << "Get window dc failed. Code - " << GetLastError();
    return "";
}
SCOPE_GUARD([hwnd, hdc] {
    ReleaseDC(hwnd, hdc);
});

//get window size
RECT clientRect;
if (hwnd)
{
    GetClientRect(hwnd, &clientRect);
}
else
{
    clientRect.top = 0;
    clientRect.left = 0;
    clientRect.right = GetSystemMetrics(SM_CXSCREEN);
    clientRect.bottom = GetSystemMetrics(SM_CYSCREEN);
}
LONG rectWidth = clientRect.right - clientRect.left;
LONG rectHeith = clientRect.bottom - clientRect.top;

//create target dc
HDC dcMemory = CreateCompatibleDC(hdc);
if (!dcMemory)
{
    LOGE << "Create compatible dc failed. Code - " << GetLastError();
    return "";
}
SCOPE_GUARD([dcMemory] {
    DeleteObject(dcMemory);
});

HBITMAP hBitmap = CreateCompatibleBitmap(hdc, rectWidth, rectHeith);
if (!hBitmap)
{
    LOGE << "Create compatible bitmap failed. Code - " << GetLastError();
    return "";
}
SCOPE_GUARD([hBitmap] {
    DeleteObject(hBitmap);
});

//select and print
{
    HGDIOBJ hOldBitmap = SelectObject(dcMemory, hBitmap);
    SCOPE_GUARD([dcMemory, hOldBitmap] {
        SelectObject(dcMemory, hOldBitmap);
    });

    if (!BitBlt(dcMemory, 0, 0, rectWidth, rectHeith, hdc, 0, 0, SRCCOPY))
    {
        LOGE << "Copy data from DC failed. Code - " << GetLastError();
        return "";
    }
}

最后,我得到了一张黑色图片。

我发现Aeroshot这样做了。它将目标窗口放在顶部并使黑色窗口返回。并在目标窗口的范围内截取Display。

我不想影响目标计划。还有其他选择吗?

0 个答案:

没有答案