Search code examples
c++qtqpixmapmouse-cursor

Qt Windows get mouse cursor icon


i am trying to get my (global) mouse cursor icon in a QPixmap.

After reading the Qt and MSDN documentation i came up with this piece of code:

I am unsure about mixing HCURSOR and HICON but i have seen some examples where they do it.

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

However, my mouseCursorPixmap size is always QSize(0,0). What goes wrong?


Solution

  • I have no idea why the code above did not work.

    However the following code example did work:

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