如何从位图对象创建光标对象

本文关键字:对象 创建 光标 位图 | 更新日期: 2023-09-27 18:18:33

假设我有一个现有的System.Drawing.Bitmap对象,我如何创建一个System.Windows.Forms.Cursor对象与我的Bitmap对象相同的像素数据?

如何从位图对象创建光标对象

这个答案取自这个问题。它允许您从位图对象创建游标并设置其热点。

public struct IconInfo
{
    public bool fIcon;
    public int xHotspot;
    public int yHotspot;
    public IntPtr hbmMask;
    public IntPtr hbmColor;
}
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetIconInfo(IntPtr hIcon, ref IconInfo pIconInfo);
[DllImport("user32.dll")]
public static extern IntPtr CreateIconIndirect(ref IconInfo icon);
/// <summary>
/// Create a cursor from a bitmap without resizing and with the specified
/// hot spot
/// </summary>
public static Cursor CreateCursorNoResize(Bitmap bmp, int xHotSpot, int yHotSpot)
{
    IntPtr ptr = bmp.GetHicon();
    IconInfo tmp = new IconInfo();
    GetIconInfo(ptr, ref tmp);
    tmp.xHotspot = xHotSpot;
    tmp.yHotspot = yHotSpot;
    tmp.fIcon = false;
    ptr = CreateIconIndirect(ref tmp);
    return new Cursor(ptr);
}

/// <summary>
/// Create a 32x32 cursor from a bitmap, with the hot spot in the middle
/// </summary>
public static Cursor CreateCursor(Bitmap bmp)
{
    int xHotSpot = 16;
    int yHotSpot = 16;
    IntPtr ptr = ((Bitmap)ResizeImage(bmp, 32, 32)).GetHicon();
    IconInfo tmp = new IconInfo();
    GetIconInfo(ptr, ref tmp);
    tmp.xHotspot = xHotSpot;
    tmp.yHotspot = yHotSpot;
    tmp.fIcon = false;
    ptr = CreateIconIndirect(ref tmp);
    return new Cursor(ptr);
}

编辑:正如在评论中指出的,当从IntPtr句柄创建Cursor时,处置游标将而不是释放句柄本身,这将创建内存泄漏,除非您自己手动使用DestroyIcon函数释放它:

[DllImport("user32.dll")]
private static extern bool DestroyIcon(IntPtr hIcon);

然后你可以像这样调用这个函数:

DestroyIcon(myCursor.Handle);