qt-获取任务栏运行的程序(二)

上一篇文章用的是普通图标的方式。那么我们想用win10风格的人任务预览怎么做呢?

  通过指定的窗口句柄,获得内存DC,然后缩小到合适比例后绘制。

  主要的代码是一个函数,如下

  

HBITMAP Widget::GetScreenCapture(HWND hwnd)
{
    if(hwnd == NULL)
        QMessageBox::warning(this, "warn!", "hwnd is illegal");

    HDC hdc = ::GetWindowDC(hwnd);
    if (hdc)
    {
        HDC hdcMem = ::CreateCompatibleDC(hdc);
        if (hdcMem)
        {
            RECT rc;
            ::GetWindowRect(hwnd, &rc);

            HBITMAP hbitmap = ::CreateCompatibleBitmap(hdc,rc.right-rc.left, rc.bottom-rc.top);
            if (hbitmap)
            {
                ::SelectObject(hdcMem, hbitmap);
                ::PrintWindow(hwnd, hdcMem, 0);
                CImage image;
                image.Attach((HBITMAP)hbitmap);
                image.Save(L"./1.bmp");
                ::DeleteObject(hbitmap);

                return hbitmap;
            }
            else
                QMessageBox::warning(this, "warn!", "get hbitmap failed!");

            ::DeleteObject(hdcMem);
        }
        else
            QMessageBox::warning(this, "warn!", "createComDC is illegal");

        ::ReleaseDC(hwnd, hdc);
    }
    else
        QMessageBox::warning(this, "warn!", "windowsDC is illegal");

    return NULL;
}

 函数返回HBITMAP后,我是在QT环境中(win32环境更简单),通过下面的代码进行转换

 //QPixmap pixmap = QtWin::fromHBITMAP(GetScreenCapture(handleWindow[i + m_nBtnMove]));
       // m_arrAction[i]->setIcon(pixmap);
        //m_arrAction[i]->setIconSize(QSize(pixmap.width(), pixmap.height()));

  然后就可以实现预览效果。所需要的头文件以及其他支持,看上一篇文章。

但是这样做有个问题,就是说如果窗口的风格是xxx,比如酷狗、IE、谷歌,那么DC拿到的就是黑色。所以解决这种问题的方法就是通过dll注射的方式,具体的我会在  qt-获取任务栏运行的程序(二)  中说明

posted @ 2017-08-30 09:30  Qt王二狗  阅读(550)  评论(0)    收藏  举报