1

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

4

1 回答 1

4

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

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

编辑:正如评论中所指出的,当CursorIntPtr句柄创建 a 时,处理光标不会释放句柄本身,这将造成内存泄漏,除非您自己使用DestroyIcon函数手动释放它:

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

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

DestroyIcon(myCursor.Handle);
于 2013-06-14T05:32:33.563 回答