【发布时间】:2012-05-20 09:52:05
【问题描述】:
问题:在循环中使用此代码 3322 次(使用底部方法 1246 次)后,在 GetHIcon() 处引发了通用 GDI+ 异常。
示例项目: http://dl.dropbox.com/u/18919663/TestGDICursorDrawing.zip
我正在尝试做的事情: 从位图中循环绘制一个新光标来做一个简单的聚焦动画。
我已经检查过的内容:我确保所有位图和图形都被处理并监控内存泄漏以确保。还要确保没有其他进程有可见的泄漏。尝试了其他方法和方法来确保正确使用位图。
Google 告诉我的: GDI+ 中似乎存在错误,没有人提供解决方案。一个人试图创建自己的位图到图标转换器,但它不够灵活,无法处理非通用图像尺寸。
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
}
【问题讨论】:
-
为什么要从位图动态创建光标?为什么不在应用程序中包含光标资源?
-
这是目前动画,所以它会是几个光标。但是,在很多情况下,当我使用它时,它是用于拖放,并且拖动图像具有反映他们拖动的内容的自定义信息,因此需要是动态的。这就是为什么我正在寻找解决方案,而不是不这样做。
-
完成后你会处理游标吗?
-
@500-InternalServerError 完成后实际上不太可能,但我可以在下次调用时执行此操作,所以我所做的就是每次设置新光标时都处理当前光标并使用了 DestroyIcon()。这样做之后,我最终让它工作了。所有其他 Dispose 工作正常,在我设置新光标之前需要进行 DestroyIcon() 调用。
标签: c# .net bitmap cursor gdi+