System.Drawing.Bitmap.GetHicon() 上的 GDI 对象泄漏

GDI Object leak on System.Drawing.Bitmap.GetHicon()

我见过类似的问题,但 none 满足我的情况。

我正在修复 C++ Windows 表单应用程序上的 GDI 对象泄漏。

这是它抛出的异常:

A generic error occurred in GDI+. at System.Drawing.Bitmap.GetHicon()

这是在发生崩溃的那一行的 GetHicon 调用:

this->notifyIcon1->Icon=Icon->FromHandle(((Bitmap^)imgsApp->Images[0])->GetHicon());

阅读此处和 https://docs.microsoft.com/en-us/dotnet/api/system.drawing.icon.fromhandle?view=net-5.0 后,我发现我需要调用 DestroyIcon() 才能释放图标句柄(不确定此处的措辞是否正确),但我由于不熟悉 Windows 表格,我无法做到这一点。

试试这个:

IntPtr iconHandle = ((Bitmap^)imgsApp->Images[0])->GetHicon();
Icon ^newIcon = Icon::FromHandle(iconHandle);
this->notifyIcon1->Icon = (Icon^) newIcon->Clone();
newIcon->Dispose();
DestroyIcon((HICON)iconHandle.ToPointer());

根据 :

Conclusion: After Icon.FromHandle, the field ownHandle is false, and thus Dispose / FromHandle won't call DestroyIcon

Therefore: if you create an Icon using Icon.FromHandle you'll have to Dispose() the Icon as well as call DestroyIcon, just as the remarks section says