假设我有一个现有System.Drawing.Bitmap
对象,如何创建一个与我的System.Windows.Forms.Cursor
对象具有相同像素数据的Bitmap
对象?
问问题
3492 次
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);
}
编辑:正如评论中所指出的,当Cursor
从IntPtr
句柄创建 a 时,处理光标不会释放句柄本身,这将造成内存泄漏,除非您自己使用DestroyIcon
函数手动释放它:
[DllImport("user32.dll")]
private static extern bool DestroyIcon(IntPtr hIcon);
然后你可以像这样调用函数:
DestroyIcon(myCursor.Handle);
于 2013-06-14T05:32:33.563 回答