1

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?

eKKiM
  • 421
  • 5
  • 18
  • Why do you think `hCursor` member of `CURSORINFO` structure is handle of an icon? – mvidelgauz Jun 30 '16 at 14:35
  • Yes, HCURSOR and HICON are identical. I have no idea why this isn't working. Does `ci.hCursor` actually contain a valid handle? If so, I imagine the problem lies with `QtWin::fromHICON`, because I've used otherwise identical code many times to obtain the mouse cursor bitmap. – Cody Gray - on strike Jun 30 '16 at 14:36
  • According to this answer: http://stackoverflow.com/questions/10469538/winapi-get-mouse-cursor-icon They are using HCURSOR in DrawIcon() – eKKiM Jun 30 '16 at 14:37

1 Answers1

2

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;
}
eKKiM
  • 421
  • 5
  • 18