示例项目:http://dl.dropbox.com/u/18919663/TestGDICursorDrawing.zip
我想做什么:从位图中绘制新的光标,以实现简单的聚焦动画。
我已经检查过的事项:确保所有的位图和图形都被处理并监控内存泄漏情况。还确保没有其他进程有可见的泄漏。尝试了其他方法和方式来确保正确地使用位图。
Google告诉我的: GDI+存在一个bug,目前没有人提供解决方案。有人尝试创建自己的位图到图标转换器,但这不足以处理非通用图像大小。
public static Cursor CreateCursor(Bitmap bmp, int xHotSpot, int yHotSpot)
{
//Shows me exactly when the error occurs.
counter++;
Console.WriteLine(counter + " GetHicon() calls");
//GetHicon() is the trouble maker.
var newCur = new Cursor(bmp.GetHicon());
bmp.Dispose();
bmp = null;
return newCur;
}
我尝试的其他方法:
public static Cursor CreateCursor(Bitmap bmp, int xHotSpot, int yHotSpot)
{
//Tried this method too, but this method results in an error with even fewer loops.
Bitmap newBitmap = new Bitmap(bmp);
// was told to try to make a new bitmap and dispose of the last to ensure that it wasn't locked or being used somewhere.
bmp.Dispose();
bmp = null;
//error occurs here.
IntPtr ptr = newBitmap.GetHicon();
ICONINFO tmp = new ICONINFO();
GetIconInfo(ptr, ref tmp);
tmp.xHotspot = xHotSpot;
tmp.yHotspot = yHotSpot;
tmp.fIcon = false;
ptr = CreateIconIndirect(ref tmp);
newBitmap.Dispose();
newBitmap = null;
return new Cursor(ptr);
}
[DllImport("user32.dll", EntryPoint = "GetIconInfo")]
public static extern bool GetIconInfo(IntPtr hIcon, ref ICONINFO piconinfo);
[DllImport("user32.dll")]
public static extern IntPtr CreateIconIndirect(ref ICONINFO icon);
[StructLayout(LayoutKind.Sequential)]
public struct ICONINFO
{
public bool fIcon; // Specifies whether this structure defines an icon or a cursor. A value of TRUE specifies
public Int32 xHotspot; // Specifies the x-coordinate of a cursor's hot spot. If this structure defines an icon, the hot
public Int32 yHotspot; // Specifies the y-coordinate of the cursor's hot spot. If this structure defines an icon, the hot
public IntPtr hbmMask; // (HBITMAP) Specifies the icon bitmask bitmap. If this structure defines a black and white icon,
public IntPtr hbmColor; // (HBITMAP) Handle to the icon color bitmap. This member can be optional if this
}