Qt Windows获取鼠标光标图标

时间:2016-06-30 14:15:16

标签: c++ qt qpixmap mouse-cursor

我想在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)。 出了什么问题?

1 个答案:

答案 0 :(得分:1)

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

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

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;
}