C# 在picturebox中显示图标时出错

C# 在picturebox中显示图标时出错,c#,winforms,icons,picturebox,C#,Winforms,Icons,Picturebox,我一直在用这段代码在图片盒中显示一个图标 Image FromIcon(Icon ico) { try { this.toolTip1.SetToolTip(pictureBox1, "The icon of the Executable"); return ico.ToBitmap(); } catch (Exception e) { this.toolTip1.SetToolTip(pictureBox1

我一直在用这段代码在图片盒中显示一个图标

Image FromIcon(Icon ico)
{
    try
    {
        this.toolTip1.SetToolTip(pictureBox1, "The icon of the Executable");
        return ico.ToBitmap();
    }
    catch (Exception e)
    {
        this.toolTip1.SetToolTip(pictureBox1, "Don't worry, it looks perfectly fine on the executable!");
        MessageBox.Show(e.Message + "\r\n" + e.StackTrace);
        Clipboard.SetText(e.Message + "\r\n" + e.StackTrace);

        // Alternate method             
        return Bitmap.FromHicon(ico.Handle);
    }
}
然而,它显示了这个错误

Requested range extends past the end of the array.
   at System.Runtime.InteropServices.Marshal.CopyToNative(Object source, Int32 startIndex, IntPtr destination, Int32 length)
   at System.Runtime.InteropServices.Marshal.Copy(Byte[] source, Int32 startIndex, IntPtr destination, Int32 length)
   at System.Drawing.Icon.ToBitmap()
图标的显示方式也很糟糕

这与我在应用程序中使用的图标相同。什么会出错

该图标与另一个图标一样为32位

如果我使用另一个图标,它工作正常,不会弹出错误


我知道这是一个老问题,但我最近遇到了同样的问题,所以我想我会为其他面临同样问题的人发布解决方案

对我来说,问题在于我是从PNG图像格式创建ICO文件的,但在.NET framework中使用这些文件的应用程序的目标版本早于4.6(即在.ICO文件中添加了对PNG帧的支持的版本)。请参见下面Icon.ToBitmap()文档中的注释:

从framework版本4.6开始,在.ico文件中添加了对PNG帧的支持。针对早期版本的框架但运行在4.6位上的应用程序可以通过在app.config文件的部分添加以下行选择加入新行为:


因此,一旦我将上述行添加到app.config文件中,它就解决了这个问题。

图像有多少位?不确定是否支持>32位(如果可能的话?@Sayse我不知道如何说出图像的位。如果你愿意,我会上传图标。我认为可能需要它,否则,请尝试使用任何其他图标并查看其是否有效使用位图。FromHicon@MrFox这是我正在使用的另一种方法,但渲染不好。