2016-06-30 326 views
0

我想讓我的(全局)鼠標光標圖標在QPixmap中。Qt Windows獲取鼠標光標圖標

閱讀Qt和MSDN文檔後,我想出了這樣一段代碼:

我不確定混合HCURSOR和惠康,但我已經看到了一些例子,他們做到這一點。

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)。 出了什麼問題?

+0

爲什麼你認爲'CURSORINFO'結構的'hCursor'成員是圖標的處理? – mvidelgauz

+0

是的,HCURSOR和HICON是相同的。我不知道爲什麼這不起作用。 'ci.hCursor'實際上是否包含有效的句柄?如果是這樣,我想'問題在於'QtWin :: fromHICON',因爲我已經多次使用相同的代碼來獲取鼠標光標位圖。 –

+0

根據這個答案:http://stackoverflow.com/questions/10469538/winapi-get-mouse-cursor-icon 他們在DrawIcon()中使用HCURSOR – eKKiM

回答

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