3

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?

orellabac
  • 2,077
  • 2
  • 26
  • 34
  • 1
    You will need to use a [constructor](https://learn.microsoft.com/en-us/dotnet/api/system.drawing.icon.-ctor?view=netframework-4.7.2). Or see [here](https://stackoverflow.com/questions/8174393/convert-bitmap-to-icon) – TaW Dec 14 '18 at 18:58

1 Answers1

4

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;
        }
    }
}
R.J. Dunnill
  • 2,049
  • 3
  • 10
  • 21
  • Thanks @r-j-dunnil – orellabac Dec 24 '18 at 16:59
  • 1
    Be careful when using that piece of code! The icon will leak memory if you will not dispose it manually! `When using this method, you must dispose of the original icon by using the DestroyIcon method in the Windows API to ensure that the resources are released.` https://learn.microsoft.com/en-us/dotnet/api/system.drawing.icon.fromhandle – DerApe Mar 08 '23 at 12:59
  • 1
    @DerApe I fixed the resource leak. Thanks for pointing that out. – R.J. Dunnill Mar 08 '23 at 22:06