I was migrating a VB6 application to C# using the VBUC but I got this error:
Cannot convert type 'System.Drawing.Image' to 'System.Drawing.Icon' and my code was:
this.Icon = (Icon) ImageList1.Images[0];
this.Text = "Edit Existing Level";
Which is the fastest in-memory way to solve this?
I wrote an extension method which converted the image to a bitmap and then to an icon:
public static class MyExtensions
{
[DllImport("user32.dll", CharSet = CharSet.Auto)]
extern static bool DestroyIcon(IntPtr handle);
public static System.Drawing.Icon ToIcon(this System.Drawing.Image instance)
{
using (System.Drawing.Bitmap bm = (System.Drawing.Bitmap)instance)
{
System.Drawing.Icon copy = null;
// Retrieve an HICON, which we are responsible for freeing.
IntPtr hIcon = bm.GetHicon();
try
{
// Create an original from the Bitmap (the HICON of which must be manually freed).
System.Drawing.Icon original = System.Drawing.Icon.FromHandle(hIcon);
// Create a copy, which owns its HICON and hence will dispose on its own.
copy = new System.Drawing.Icon(original, original.Size);
}
finally
{
// Free the original Icon handle (as its finalizer will not).
DestroyIcon(hIcon);
}
// Return the copy, which has a self-managing lifetime.
return copy;
}
}
}