假设我有一个现有的System.Drawing.Bitmap
对象,如何使用与System.Windows.Forms.Cursor
对象相同的像素数据创建Bitmap
对象?
答案 0 :(得分:2)
此答案取自this question。它允许您从Bitmap对象创建Cursor并设置其热点。
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);
}
修改:正如评论中所指出的,当从Cursor
句柄创建IntPtr
时,处理游标将不发布句柄本身会产生内存泄漏,除非您使用DestroyIcon
函数手动释放它:
[DllImport("user32.dll")]
private static extern bool DestroyIcon(IntPtr hIcon);
然后你可以这样调用这个函数:
DestroyIcon(myCursor.Handle);