c# - 在图片框中显示图标时出错

标签 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, "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()

图标也以令人讨厌的方式显示,

enter image description here

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

那个图标和另一个一样是 32 位的。

enter image description here

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

enter image description here

最佳答案

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

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

Beginning with framework version 4.6 support was added for PNG frames in .ico files. Applications that target earlier versions of the framework but are running on the 4.6 bits can opt in into the new behavior by adding the following line to the <runtime> section of the app.config file:<AppContextSwitchOverrides value="Switch.System.Drawing.DontSupportPngFramesInIcons=false" />

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

关于c# - 在图片框中显示图标时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18381643/

相关文章:

c# - 使用 ADAL.js 获取的 token 对 Azure 移动服务应用程序进行身份验证

c# - Asp.net MVC - 在 cshtml 页面中创建环境特定的元标记

c# - 如何将 SelectedNodeChanged 事件添加到 winform TreeView ?

react-native - 场景、选项卡 (react-native-router-flux) 和图标 (react-native-vector-icons)

css - SVG 动画图标使用 css 使尺寸更大

html - 如何更改 Facebook Font Awesome 图标的颜色?

c# - 当我从具有多个表单的 View 提交表单时,为什么我的 Controller 中会收到空值?使用 ASP.NET Core 5 MVC

C# 在特定内存地址创建对象

.net - setter中的数据绑定(bind)和抛出异常

c# - 如何在 MessageBox.show 中创建超链接?