Uso dei cursori

In questa sezione vengono illustrati gli argomenti seguenti.

Creazione di un cursore

L'esempio seguente crea due handle di cursore: uno per il cursore di clessidra standard e uno per un cursore personalizzato incluso come risorsa nel file di definizione delle risorse dell'applicazione.

HCURSOR hCurs1 = LoadCursor(NULL, IDC_WAIT);
HCURSOR hCurs2 = LoadCursor(hInstance, MAKEINTRESOURCE(IDC_MYICON));

Le applicazioni devono implementare cursori personalizzati come risorse e usare LoadCursor, LoadCursorFromFileo LoadImage anziché creare il cursore in fase di esecuzione. L'uso delle risorse cursori evita la dipendenza dei dispositivi, semplifica la localizzazione e consente alle applicazioni di condividere le progettazioni dei cursori.

Nell'esempio seguente viene usata la funzioneCreateCursorper creare un cursore monocromatico personalizzato in fase di esecuzione. L'esempio è incluso qui per illustrare come il sistema interpreta le maschere di cursore.

Ogni pixel nella mappa del cursore è rappresentato da un singolo carattere:

Symbol AND bit bit di XOR Visualizzare
1 0 Transparent
X 1 1 Inverti schermo
o 0 1 Bianco
+ 0 0 Nero
#define CURSOR_SIZE 32

// Symbol encoding: ' '=transparent  'o'=white  '+'=black
static const char *const yin_cursor[CURSOR_SIZE] = {
    "              ++++              ",
    "          ++++oooo+             ",
    "        ++oooooo++              ",
    "       +ooooooo+                ",
    "     +oooooooo+                 ",
    "    +oooooooo+                  ",
    "    +oooooooo+                  ",
    "   +oooooooo+                   ",
    "  +ooooooooo+                   ",
    "  +oooooooo+                    ",
    " +ooooooooo+                    ",
    " +ooooooooo+                    ",
    " +oooooooooo+                   ",
    "+ooooooooooo+                   ",
    "+oooooooooooo+                  ",
    "+ooooooooooooo++                ",
    "+ooooooooooooooo+               ",
    "+oooooooooooooooo++             ",
    "+oooooooooooooooooo+            ",
    " +ooooooooooooooooo+            ",
    " +oooooooo+++ooooooo+           ",
    " +ooooooo+++++oooooo+           ",
    "  +oooooo+++++oooooo+           ",
    "  +oooooo+++++ooooo+            ",
    "   +oooooo+++oooooo+            ",
    "    +ooooooooooooo+             ",
    "    +ooooooooooooo+             ",
    "     ++oooooooooo+              ",
    "       +oooooooo+               ",
    "        ++oooo++                ",
    "          ++++                  ",
    "                                ",
};

// Pack an XPM-style cursor map into separate 1bpp AND and XOR bit planes.
// Output buffers must be sized: ((w + 15) / 16) * 2 * h bytes.
static void PackCursorMasks(const char *const rows[], int w, int h,
                             BYTE *pbAnd, BYTE *pbXor)
{
    int stride = ((w + 15) / 16) * 2;  // WORD-aligned row stride, per CreateCursor contract
    ZeroMemory(pbAnd, stride * h);
    ZeroMemory(pbXor, stride * h);
    for (int y = 0; y < h; y++) {
        for (int x = 0; x < w; x++) {
            BYTE bit = (BYTE)(0x80 >> (x % 8));
            int  idx = y * stride + x / 8;
            char sym = rows[y][x];
            if (sym == ' ' || sym == 'X') pbAnd[idx] |= bit;
            if (sym == 'o' || sym == 'X') pbXor[idx] |= bit;
        }
    }
}

// Row stride for a 32-pixel-wide 1bpp mask: ((32 + 15) / 16) * 2 = 4 bytes.
BYTE abAnd[CURSOR_SIZE * 4];
BYTE abXor[CURSOR_SIZE * 4];
PackCursorMasks(yin_cursor, CURSOR_SIZE, CURSOR_SIZE, abAnd, abXor);

// hInstance is the application's HINSTANCE from WinMain.
// Call DestroyCursor when the cursor is no longer needed.
HCURSOR hCurs3 = CreateCursor(
    hInstance,  // application instance
    19,         // hot spot x
    2,          // hot spot y
    CURSOR_SIZE,
    CURSOR_SIZE,
    abAnd,
    abXor);

Per altre informazioni, vedere Bitmaps.

Uso di funzioni cursore per creare un mousetrap

Nell'esempio seguente vengono usate le funzioni SetCursorPos, GetCursorPos, CreateCursor, CreateIcon, SetCursor e DrawIconEx per creare un semplice mousetrap. Al centro della finestra viene disegnata un'icona a forma di yang. Se il cursore non si sposta per 3 secondi, si aggancia all'icona yang e assume la forma yin. Muovendo il mouse si reimposta la trappola.

// PackCursorMasks, yin_cursor, and CURSOR_SIZE are defined in the preceding example.

#define ICON_SIZE     32
#define YIN_HOT_X     19
#define YIN_HOT_Y      2
#define IDT_CURSOR     1
#define TRAP_DELAY  3000    // ms of inactivity before the cursor snaps to the icon

// Symbol encoding: ' '=transparent  'o'=white  '+'=black
static const char *const yang_icon[ICON_SIZE] = {
    "                                ",
    "                  ++++          ",
    "                ++++++++        ",
    "               ++++++++++       ",
    "              +++++++++++++     ",
    "             +++++++++++++++    ",
    "             +++++++++++++++    ",
    "            ++++++ooo++++++++   ",
    "            +++++ooooo++++++++  ",
    "           ++++++ooooo++++++++  ",
    "           ++++++ooooo+++++++++ ",
    "           +++++++ooo++++++++++ ",
    "            +++++++++++++++++++ ",
    "            ++++++++++++++++++++",
    "             +++++++++++++++++++",
    "              ++++++++++++++++++",
    "                ++++++++++++++++",
    "                 +++++++++++++++",
    "                   +++++++++++++",
    "                   ++++++++++++ ",
    "                    +++++++++++ ",
    "                    +++++++++++ ",
    "                    ++++++++++  ",
    "                   +++++++++++  ",
    "                   ++++++++++   ",
    "                  ++++++++++    ",
    "                  ++++++++++    ",
    "                 ++++++++++     ",
    "                +++++++++       ",
    "              ++++++++++        ",
    "             +++++++++          ",
    "              ++++              ",
};

static HICON   hYang;
static HCURSOR hYin;
static POINT   ptLast;
static BOOL    bTrapped;

LRESULT CALLBACK MainWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch (uMsg)
    {
        case WM_CREATE:
        {
            HINSTANCE hInstance = ((LPCREATESTRUCT)lParam)->hInstance;

            BYTE abAndIcon[ICON_SIZE * 4];
            BYTE abXorIcon[ICON_SIZE * 4];
            PackCursorMasks(yang_icon, ICON_SIZE, ICON_SIZE, abAndIcon, abXorIcon);
            hYang = CreateIcon(hInstance, ICON_SIZE, ICON_SIZE, 1, 1,
                               abAndIcon, abXorIcon);

            BYTE abAndCursor[CURSOR_SIZE * 4];
            BYTE abXorCursor[CURSOR_SIZE * 4];
            PackCursorMasks(yin_cursor, CURSOR_SIZE, CURSOR_SIZE, abAndCursor, abXorCursor);
            hYin = CreateCursor(hInstance, YIN_HOT_X, YIN_HOT_Y, CURSOR_SIZE, CURSOR_SIZE,
                                abAndCursor, abXorCursor);

            GetCursorPos(&ptLast);
            SetTimer(hWnd, IDT_CURSOR, TRAP_DELAY, (TIMERPROC)NULL);
            return 0;
        }

        case WM_PAINT:
        {
            PAINTSTRUCT ps;
            HDC hDC = BeginPaint(hWnd, &ps);
            RECT rc;
            GetClientRect(hWnd, &rc);
            DrawIconEx(hDC,
                       (rc.right  - ICON_SIZE) / 2,
                       (rc.bottom - ICON_SIZE) / 2,
                       hYang, ICON_SIZE, ICON_SIZE, 0, NULL, DI_NORMAL);
            EndPaint(hWnd, &ps);
            return 0;
        }

        case WM_MOUSEMOVE:
        {
            POINT ptNow;
            GetCursorPos(&ptNow);
            if (ptNow.x != ptLast.x || ptNow.y != ptLast.y)
            {
                ptLast = ptNow;
                bTrapped = FALSE;
                SetTimer(hWnd, IDT_CURSOR, TRAP_DELAY, (TIMERPROC)NULL);
            }
            break;
        }

        case WM_TIMER:
        {
            POINT ptNow;
            GetCursorPos(&ptNow);
            if (ptNow.x == ptLast.x && ptNow.y == ptLast.y)
            {
                RECT rc;
                GetClientRect(hWnd, &rc);
                POINT ptTarget = {
                    (rc.right  - ICON_SIZE) / 2 + YIN_HOT_X,
                    (rc.bottom - ICON_SIZE) / 2 + YIN_HOT_Y
                };
                ClientToScreen(hWnd, &ptTarget);
                SetCursorPos(ptTarget.x, ptTarget.y);
                // Ignore the mouse-move notification generated by this repositioning.
                GetCursorPos(&ptLast);
                SetCursor(hYin);
                bTrapped = TRUE;
                KillTimer(hWnd, IDT_CURSOR);
            }
            else
            {
                // Movement outside this window does not generate WM_MOUSEMOVE here.
                ptLast = ptNow;
            }
            return 0;
        }

        case WM_SETCURSOR:
            if (bTrapped)
            {
                SetCursor(hYin);
                return TRUE;
            }
            break;

        case WM_DESTROY:
            KillTimer(hWnd, IDT_CURSOR);
            DestroyCursor(hYin);
            DestroyIcon(hYang);
            PostQuitMessage(0);
            return 0;
    }

    return DefWindowProc(hWnd, uMsg, wParam, lParam);
}

Creazione di un cursore con fusione alfa

Seguire questa procedura per creare un cursore o un'icona con fusione alfa in fase di esecuzione:

  • Riempire bitmapINFOHEADER per un DIB dall'alto verso il basso (biBitCount=32, biCompression=BI_RGB, biHeight negativo) e chiamare CreateDIBSection per ottenere la bitmap del colore. Riutilizzare la stessa intestazione con biBitCount=1 per creare la maschera AND 1bpp.
  • Disegnare l'immagine del cursore nella sezione DIB a colori e impostare il byte alfa di ogni pixel.
  • Riempire la maschera AND: impostare ogni bit su 0 (opaco) dove alpha > 0, e su 1 (trasparente) dove alpha == 0.
  • Compilare una struttura ICONINFO con la sezione DIB come hbmColor e la maschera AND come hbmMask.
  • Chiamare CreateIconIndirect per creare il cursore o l'icona.

Il codice seguente illustra come creare un cursore con fusione alfa. DrawRGBCircles scrive tre cerchi R/G/B semitrasparnti sovrapposti direttamente in un buffer di pixel: composita i cerchi in modo analitico usando la formula AC_SRC_OVER e archivia i canali RGB premoltiplicati con alfa in rgbReserved. Le dimensioni del cursore vengono lette da GetSystemMetrics in modo che corrispondano all'impostazione delle dimensioni del cursore di sistema. Passare fIcon a TRUE per creare un'icona.

#define WIDTHBYTES(bits) ((DWORD)(((bits) + 31) & ~31) / 8)

// Fill pixels (top-down, cx-cy) with three overlapping R/G/B circles, each alpha=128.
// Composites with AC_SRC_OVER and preserves premultiplied RGB channels.
static void DrawRGBCircles(RGBQUAD *pixels, int cx, int cy)
{
    // r = cx/3: each center is r px from its nearest edge, so the circle touches exactly.
    const int r = cx / 3;
    struct { int x, y; RGBQUAD color; } circles[3] = {
        //                  B    G    R    A
        { cx / 2,  r,      {  0,   0, 255, 128 } },  // red,   top-center
        { r,       cy - r, {  0, 255,   0, 128 } },  // green, bottom-left
        { cx - r,  cy - r, {255,   0,   0, 128 } },  // blue,  bottom-right
    };

    for (int y = 0; y < cy; y++) {
        for (int x = 0; x < cx; x++) {
            DWORD R = 0, G = 0, B = 0, A = 0;
            for (int i = 0; i < 3; i++) {
                int dx = x - circles[i].x, dy = y - circles[i].y;
                if (dx*dx + dy*dy > r*r) continue;
                DWORD a = circles[i].color.rgbReserved, inv = 255 - a;
                // AC_SRC_OVER (premultiplied): dst = src + dst * (1 - src_a/255)
                R = circles[i].color.rgbRed   * a / 255 + R * inv / 255;
                G = circles[i].color.rgbGreen * a / 255 + G * inv / 255;
                B = circles[i].color.rgbBlue  * a / 255 + B * inv / 255;
                A = a                                    + A * inv / 255;
            }
            RGBQUAD *p = &pixels[y * cx + x];
            p->rgbReserved = (BYTE)A;
            p->rgbRed   = (BYTE)R;
            p->rgbGreen = (BYTE)G;
            p->rgbBlue  = (BYTE)B;
        }
    }
}

HCURSOR CreateAlphaCursor(void)
{
    int cx = GetSystemMetrics(SM_CXCURSOR);
    int cy = GetSystemMetrics(SM_CYCURSOR);

    // Extra RGBQUAD at the end for the 1bpp colour table (index 1 = white).
    BYTE bmiBuffer[sizeof(BITMAPINFO) + sizeof(RGBQUAD)] = {0};
    BITMAPINFO *pBmi = (BITMAPINFO *)bmiBuffer;
    pBmi->bmiHeader.biSize        = sizeof(pBmi->bmiHeader);
    pBmi->bmiHeader.biWidth       = cx;
    pBmi->bmiHeader.biHeight      = -cy;   // negative = top-down
    pBmi->bmiHeader.biPlanes      = 1;
    pBmi->bmiHeader.biCompression = BI_RGB;

    // Create a top-down 32bpp DIB section for the color (XOR) image.
    pBmi->bmiHeader.biBitCount = 32;
    RGBQUAD *lpBits;
    HBITMAP hBitmap = CreateDIBSection(NULL, pBmi, DIB_RGB_COLORS, (void **)&lpBits, NULL, 0);

    DrawRGBCircles(lpBits, cx, cy);

    // Reuse the same header for the 1bpp AND mask; switch biBitCount and set the colour table.
    pBmi->bmiHeader.biBitCount = 1;
    pBmi->bmiColors[0].rgbRed = pBmi->bmiColors[0].rgbGreen = pBmi->bmiColors[0].rgbBlue = 0;
    pBmi->bmiColors[1].rgbRed = pBmi->bmiColors[1].rgbGreen = pBmi->bmiColors[1].rgbBlue = 255;
    BYTE *andBits;
    HBITMAP hMaskBitmap = CreateDIBSection(NULL, pBmi, DIB_RGB_COLORS, (void **)&andBits, NULL, 0);

    // Set AND mask: bit=1 (transparent) wherever no circle was drawn.
    int maskStride = WIDTHBYTES(cx * 1);
    for (int y = 0; y < cy; y++) {
        for (int x = 0; x < cx; x++) {
            if (lpBits[y * cx + x].rgbReserved == 0)
                andBits[y * maskStride + x / 8] |= (BYTE)(0x80 >> (x % 8));
        }
    }

    ICONINFO ii = {0};
    ii.fIcon     = FALSE;
    ii.xHotspot  = cx / 2;
    ii.yHotspot  = cy / 2;
    ii.hbmMask   = hMaskBitmap;
    ii.hbmColor  = hBitmap;

    HCURSOR hCursor = (HCURSOR)CreateIconIndirect(&ii);

    DeleteObject(hBitmap);
    DeleteObject(hMaskBitmap);

    return hCursor;
}

Prima di chiudere, è necessario usare la funzioneDestroyCursor per eliminare tutti i cursori creati con CreateCursor o CreateIconIndirect. Non è necessario eliminare i cursori creati da altre funzioni.

Ottenere una dimensione del cursore

Nell'esempio seguente vengono recuperate le dimensioni di un cursore o di un'icona dal relativo handle:

BOOL GetCursorDimensions(_In_ HCURSOR hcur, _Out_ SIZE *psiz)
{
    ICONINFO ii;
    BOOL fResult = GetIconInfo(hcur, &ii);
    if (fResult) {
        BITMAP bm;
        fResult = GetObject(ii.hbmMask, sizeof(bm), &bm) == sizeof(bm);
        if (fResult) {
            psiz->cx = bm.bmWidth;
            psiz->cy = ii.hbmColor ? bm.bmHeight : bm.bmHeight / 2;
        }
        DeleteObject(ii.hbmMask);
        if (ii.hbmColor) DeleteObject(ii.hbmColor);
    }
    return fResult;
}

Visualizzazione di un cursore

Il sistema visualizza automaticamente il cursore della classe (il cursore associato alla finestra a cui punta il cursore). È possibile assegnare un cursore di classe durante la registrazione di una classe window. L'esempio seguente illustra questa situazione assegnando un handle di cursore al membro hCursor della strutturaWNDCLASSidentificata dal parametro wc.

WNDCLASS wc = {0};
wc.lpfnWndProc   = MainWndProc;
wc.hInstance     = hInstance;
wc.hIcon         = LoadIcon(NULL, IDI_APPLICATION);
wc.hCursor       = LoadCursor(hInstance, MAKEINTRESOURCE(IDC_MYICON));
wc.hbrBackground = GetStockObject(WHITE_BRUSH);
wc.lpszMenuName  = TEXT("GenericMenu");
wc.lpszClassName = TEXT("GenericWClass");

return RegisterClass(&wc);

Quando la classe window viene registrata, il cursore identificato da IDC_MYICON nel file di definizione delle risorse dell'applicazione è il cursore predefinito per tutte le finestre basate sulla classe .

L'applicazione può modificare la progettazione del cursore usando la funzione SetCursor e specificando un handle di cursore diverso. Tuttavia, quando il cursore si sposta, il sistema ridisegna il cursore della classe in corrispondenza della nuova posizione. Per evitare che il cursore della classe venga ridisegnato, è necessario elaborare il messaggio di WM_SETCURSOR. Ogni volta che il cursore si sposta e l'input del mouse non viene acquisito, il sistema invia questo messaggio alla finestra in cui viene spostato il cursore.

È possibile specificare cursori diversi per condizioni diverse durante l'elaborazione WM_SETCURSOR. Controllare LOWORD(lParam) per distinguere l'area client dalle aree non client, quali le maniglie di ridimensionamento; passare gli hit test non client a DefWindowProc in modo che il sistema imposti lì il cursore di sistema appropriato.

case WM_SETCURSOR:
    if (LOWORD(lParam) == HTCLIENT)
    {
        SetCursor(hCurs3);
        return TRUE;
    }
    return DefWindowProc(hWnd, uMsg, wParam, lParam);

La restituzione di TRUE impedisce a DefWindowProc di reimpostare il cursore al cursore della classe. Il passaggio degli eventi dell’area non client a DefWindowProc preserva i cursori di sistema per il ridimensionamento e lo spostamento.

È possibile sostituire un cursore di classe usando la funzione SetClassLongPtr . Questa funzione modifica le impostazioni predefinite della finestra per tutte le finestre di una classe specificata. Nell'esempio seguente viene sostituito il cursore di classe esistente con il cursore hCurs2.

SetClassLongPtr(hWnd, GCLP_HCURSOR, (LONG_PTR)hCurs2);

Per altre informazioni, vedere classi di finestre e input del mouse.

Limitare un cursore

L'esempio seguente limita il cursore alla finestra dell'applicazione e quindi ripristina il cursore nella finestra precedente. Nell'esempio viene utilizzata la funzione GetClipCursor per registrare l'area in cui il cursore può spostarsi e la funzioneclipCursorper limitare e ripristinare il cursore.

RECT rcOldClip;
GetClipCursor(&rcOldClip);

RECT rcClip;
GetWindowRect(hWnd, &rcClip);
ClipCursor(&rcClip);

// ... process input from the confined cursor ...

ClipCursor(&rcOldClip);

Poiché nel sistema è disponibile un solo cursore alla volta, un'applicazione che limita il cursore deve ripristinare il cursore prima di rinunciare al controllo in un'altra finestra.

Uso della tastiera per spostare il cursore

Poiché il sistema non richiede un mouse, un'applicazione deve essere in grado di simulare le azioni del mouse con la tastiera. L'esempio seguente illustra come raggiungere questo obiettivo usando le funzioni GetCursorPos e SetCursorPos ed elaborando l'input dai tasti di direzione.

static int nRepeat = 1;

switch (uMsg)
{
    case WM_KEYDOWN:
    {
        int dx = 0, dy = 0;
        switch (wParam)
        {
            case VK_LEFT:  dx = -nRepeat; break;
            case VK_RIGHT: dx = +nRepeat; break;
            case VK_UP:    dy = -nRepeat; break;
            case VK_DOWN:  dy = +nRepeat; break;
            default: return DefWindowProc(hWnd, uMsg, wParam, lParam);
        }

        POINT pt;
        GetCursorPos(&pt);
        ScreenToClient(hWnd, &pt);
        pt.x += dx;
        pt.y += dy;

        RECT rc;
        GetClientRect(hWnd, &rc);
        if (pt.x < rc.left)         pt.x = rc.left;
        else if (pt.x >= rc.right)  pt.x = rc.right - 1;
        if (pt.y < rc.top)          pt.y = rc.top;
        else if (pt.y >= rc.bottom) pt.y = rc.bottom - 1;

        ClientToScreen(hWnd, &pt);
        SetCursorPos(pt.x, pt.y);
        if (nRepeat < 32) nRepeat++;
        return 0;
    }
    case WM_KEYUP:
        nRepeat = 1;
        return 0;
}