Qt Windows 获取鼠标光标图标

Qt Windows get mouse cursor icon

我正在尝试在 QPixmap 中获取我的(全局)鼠标光标图标。

在阅读了 Qt 和 MSDN 文档后,我想到了这段代码:

我不确定混合使用 HCURSOR 和 HICON,但我看到了一些他们这样做的例子。

QPixmap MouseCursor::getMouseCursorIconWin()
{
    CURSORINFO ci;
    ci.cbSize = sizeof(CURSORINFO);

    if (!GetCursorInfo(&ci))
        qDebug() << "GetCursorInfo fail";

    QPixmap mouseCursorPixmap = QtWin::fromHICON(ci.hCursor);
    qDebug() << mouseCursorPixmap.size();

    return mouseCursorPixmap;
}

但是,我的 mouseCursorPixmap 大小始终是 QSize(0,0)。 出了什么问题?

我不知道为什么上面的代码不起作用。

但是以下代码示例确实有效:

QPixmap MouseCursor::getMouseCursorIconWin()
{
    // Get Cursor Size
    int cursorWidth = GetSystemMetrics(SM_CXCURSOR);
    int cursorHeight = GetSystemMetrics(SM_CYCURSOR);

    // Get your device contexts.
    HDC hdcScreen = GetDC(NULL);
    HDC hdcMem = CreateCompatibleDC(hdcScreen);

    // Create the bitmap to use as a canvas.
    HBITMAP hbmCanvas = CreateCompatibleBitmap(hdcScreen, cursorWidth, cursorHeight);

    // Select the bitmap into the device context.
    HGDIOBJ hbmOld = SelectObject(hdcMem, hbmCanvas);

    // Get information about the global cursor.
    CURSORINFO ci;
    ci.cbSize = sizeof(ci);
    GetCursorInfo(&ci);

    // Draw the cursor into the canvas.
    DrawIcon(hdcMem, 0, 0, ci.hCursor);

    // Convert to QPixmap
    QPixmap cursorPixmap = QtWin::fromHBITMAP(hbmCanvas, QtWin::HBitmapAlpha);

    // Clean up after yourself.
    SelectObject(hdcMem, hbmOld);
    DeleteObject(hbmCanvas);
    DeleteDC(hdcMem);
    ReleaseDC(NULL, hdcScreen);

    return cursorPixmap;
}