Windows中使用GDI抓图

发布时间 2023-05-25 10:29:52作者: TechNomad

首先在pro文件中添加gdi32

QT       += core gui winextras

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

CONFIG += c++11

# The following define makes your compiler emit warnings if you use
# any Qt feature that has been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

LIBS += -lgdi32

# You can also make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

SOURCES += \
    main.cpp \
    screen_capture.cpp

HEADERS += \
    screen_capture.h

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

截取屏幕图像源码如下:

#include <QDateTime>
#include <QDebug>
#include <QPixmap>
#include <QtWin>
#include <Windows.h>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    // 获取屏幕的设备上下文
    HDC hScreenDC = GetDC(NULL);

    // 获取屏幕的宽度和高度
    int screenWidth = GetSystemMetrics(SM_CXSCREEN);
    int screenHeight = GetSystemMetrics(SM_CYSCREEN);

    int counts = 0;
    /* 每隔1秒获取一次图像 */
    while (counts < 5) {
        QString fileName = QString("%1.png").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd-hh-mm-ss"));
        qDebug() << fileName;

        // 创建一个内存设备上下文
        HDC hMemDC = CreateCompatibleDC(hScreenDC);

        // 创建一个位图对象,用于存储屏幕图像
        HBITMAP hBitmap = CreateCompatibleBitmap(hScreenDC, screenWidth, screenHeight);

        // 将位图对象选入内存设备上下文
        HBITMAP hOldBitmap = (HBITMAP)SelectObject(hMemDC, hBitmap);

        // 从屏幕设备上下文复制图像到内存设备上下文
        BitBlt(hMemDC, 0, 0, screenWidth, screenHeight, hScreenDC, 0, 0, SRCCOPY);

        QPixmap pixmap = QtWin::fromHBITMAP(hBitmap);
        pixmap.save(fileName, "PNG");

        // 清理资源
        SelectObject(hMemDC, hOldBitmap);
        DeleteObject(hBitmap);
        DeleteDC(hMemDC);

        counts++;
        Sleep(1000);
    }

    ReleaseDC(nullptr, hScreenDC);

    return a.exec();
}