Sri Harsha Chilakapati
Sri Harsha Chilakapati

Reputation: 11950

Error showing Icon in picturebox

I've been using this code to show an icon in a 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);
    }
}

However it is showing this error.

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()

Also the icon is shown in a nasty way,

enter image description here

That's the same icon I use for my application. What can go wrong?

That icon is 32 bit as well as the other.

enter image description here

If I use another icon, it works fine and no error pops up.

enter image description here

Upvotes: 2

Views: 1544

Answers (1)

michealt17
michealt17

Reputation: 148

I know this is an old question but I recently came across the same issue so thought I would post the resolution for anyone else facing the same problem.

For me, the issue was that I was creating the ICO files from PNG image formats but the application that the files were used in targeted a .NET framework that was earlier than 4.6 (i.e. the version in which support was added for PNG frames in .ico files). See note from the Icon.ToBitmap() documentation below:

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" />

So once I added the above line to the app.config file it resolved the issue.

Upvotes: 1

Related Questions