Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot convert type 'System.Drawing.Image' to 'System.Drawing.Icon'

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?

like image 900
orellabac Avatar asked Feb 17 '26 12:02

orellabac


1 Answers

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;
        }
    }
}
like image 155
R.J. Dunnill Avatar answered Feb 20 '26 02:02

R.J. Dunnill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!