使用游标

本部分讨论以下主题。

创建游标

以下示例创建两个游标句柄:一个用于标准沙漏游标,一个用于作为应用程序资源定义文件中的资源包含的自定义游标。

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

应用程序应实现自定义游标作为资源,并使用 LoadCursor、 LoadCursorFromFile 或 LoadImage ,而不是在运行时创建游标。 使用游标资源可避免设备依赖、简化本地化,并使应用程序能够共享游标设计。

以下示例使用 CreateCursor 函数在运行时创建自定义单色游标。 此处提供了该示例来说明系统如何解释游标掩码。

游标映射中的每个像素都由一个字符表示:

符号 AND 位 XOR 位 显示位置
1 0 Transparent
X 1 1 反转屏幕
o 0 1 白色
+ 0 0 黑色
#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);

有关详细信息,请参阅位图。

使用游标函数创建捕鼠器

以下示例使用 SetCursorPos、GetCursorPos、CreateCursor、CreateIcon、SetCursor 和 DrawIconEx 函数来创建一个简单的鼠标陷阱。 在窗口中央绘制一个阳形图标。 如果光标 3 秒内未移动,它会自动吸附到阳图标并变为阴形状。 移动鼠标会重置陷阱。

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

创建 Alpha 混合光标

按照以下步骤在运行时创建 alpha 混合光标或图标:

  • 为自上而下的 DIB 填充 biCompression=BI_RGB(biHeight、、 为负),并调用 CreateDIBSection 以获取颜色位图。 重复使用同一标头 biBitCount=1 来创建 1bpp AND 掩码。
  • 将光标图像绘制到颜色 DIB 节中,并设置每个像素的 Alpha 字节。
  • 填充 AND 掩码:将每个位在 alpha > 0 处设为 0(不透明),在 alpha == 0 处设为 1(透明)。
  • 用作为 的 DIB 节和作为 的 AND 掩码填充 hbmMask 结构。
  • 调用 CreateIconIndirect 创建游标或图标。

以下代码演示如何创建 alpha 混合游标。 DrawRGBCircles将三个重叠的 R/G/B 半透明圆直接写入像素缓冲区:它使用 AC_SRC_OVER 公式以解析方式合成这些圆,并将预乘的 RGB 通道与 alpha 一起存储在 rgbReserved 中。 从 GetSystemMetrics 读取游标大小以匹配系统游标大小设置。 将 TRUE 更改为 fIcon,以创建图标。

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

在关闭之前,必须使用 DestroyCursor 函数销毁使用 CreateCursor 或 CreateIconIndirect 创建的任何游标。 不需要销毁由其他函数创建的游标。

获取光标大小

以下示例从光标或图标的句柄中检索其维度:

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

显示光标

系统会自动显示类游标(与光标指向的窗口关联的游标)。 注册窗口类时,可以分配类游标。 以下示例通过将游标句柄分配给由 wc 参数标识的 WNDCLASS 结构的 hCursor 成员来说明这一点。

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

注册窗口类时,应用程序资源定义文件中标识 IDC_MYICON 的游标是基于该类的所有窗口的默认游标。

应用程序可以使用 SetCursor 函数和指定不同的游标句柄来更改游标的设计。 但是,当游标移动时,系统会在新位置重新绘制类游标。 若要防止重新绘制类游标,必须处理 WM_SETCURSOR 消息。 每次未捕获光标移动和鼠标输入时,系统都会将此消息发送到光标移动的窗口。

可以在处理 WM_SETCURSOR时为不同的条件指定不同的游标。 检查 LOWORD(lParam) 以区分工作区与非客户端区域,例如调整句柄的大小;将非客户端命中传递给 DefWindowProc ,以便系统在此处设置相应的系统游标。

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

TRUE返回可防止 DefWindowProc 将游标重置为类游标。 将非客户端区域命中交给 DefWindowProc 处理,可保留系统调整大小和移动光标。

可以使用 SetClassLongPtr 函数替换类游标。 此函数更改指定类的所有窗口的默认窗口设置。 以下示例将现有类游标替换为 hCurs2 游标。

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

有关详细信息,请参阅 窗口类 和 鼠标输入。

限制光标

以下示例将光标限制为应用程序的窗口,然后将光标还原到其上一个窗口。 该示例使用 GetClipCursor 函数来记录游标可移动的区域以及 ClipCursor 函数来限制和还原游标。

RECT rcOldClip;
GetClipCursor(&rcOldClip);

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

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

ClipCursor(&rcOldClip);

由于系统一次只能使用一个光标,因此将光标限制在特定区域内的应用程序必须先恢复光标,然后才能将控制权交给另一个窗口。

使用键盘移动光标

由于系统不需要鼠标,因此应用程序应能够使用键盘模拟鼠标作。 以下示例演示如何通过使用 GetCursorPos 和 SetCursorPos 函数以及处理箭头键的输入来实现此目的。

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