无法将类型'System.Drawing.Image'转换为'System.Drawing.Icon'。

3

我正在使用VBUC将VB6应用程序迁移到C#,但出现了以下错误:

无法将类型“System.Drawing.Image”转换为“System.Drawing.Icon”,我的代码如下:

    this.Icon = (Icon) ImageList1.Images[0];
    this.Text = "Edit Existing Level";

哪种最快的内存方式可以解决这个问题?

1
你需要使用一个构造函数。或者查看这里 - TaW
1个回答

4
我写了一个扩展方法,将图像转换为位图,然后再转换为图标:
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-dunnil - orellabac
1
使用那段代码时要小心!如果不手动释放,图标将会泄露内存!“使用此方法时,必须使用Windows API中的DestroyIcon方法处理原始图标以确保释放资源。” https://learn.microsoft.com/en-us/dotnet/api/system.drawing.icon.fromhandle - DerApe
1
@DerApe 我修复了资源泄漏问题。感谢指出。 - R.J. Dunnill

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接