I was wondering whether it's possible to validate a required size for an icon before trying:
Dim myIcon = New Icon(theIcon, requestedSize).
This falls over for negative numbers, so that's an easy check.
It appears it falls over if the number is less than half of the smallest icon. I've looked at the icon class but can see nothing for extracting the sizes.
ETA:
This is pretty annoying. You can put Int32.MaxValue in and it chooses the largest icon. Why it doesn't choose the smallest icon, as long as size > 0 I don't know. If I can determine the size of the smallest icon, then I can do that myself - with no need to throw an exception.
ETA:
Here's some VB code for anyone who's interested:
//Returns an array of IconMetaData which contains, amongst other things, the size of
// each image in the icon.
<Extension()> _
Public Function GetMetaData(ByVal icon As Icon) As IconMetaData()
Using s As New System.IO.MemoryStream
icon.Save(s)
Using r As New BinaryReader(s)
s.Position = 0
Dim Header As New IconHeader(r)
Dim Data As New List(Of IconMetaData)
For i As Integer = 0 To Header.NumberOfIcons - 1
Dim d As New IconMetaData(r)
*See note below.
If d.Height <> 0 AndAlso d.Width <> 0 Then
Data.Add(d)
End If
Next
Return Data.ToArray
End Using
End Using
End Function
Private Class IconHeader
Public ReadOnly NumberOfIcons As Short
Public Sub New(ByVal r As BinaryReader)
r.ReadInt16() //Reserved
r.ReadInt16() //Type, 0=Bitmap, 1=Icon
Me.NumberOfIcons = r.ReadInt16
End Sub
End Class
Public Class IconMetaData
Public ReadOnly Width As Byte
Public ReadOnly Height As Byte
Public ReadOnly ColorCount As Byte
Public ReadOnly Planes As Short
Public ReadOnly BitCount As Short
Friend Sub New(ByVal r As BinaryReader)
Me.Width = r.ReadByte
Me.Height = r.ReadByte
Me.ColorCount = r.ReadByte
r.ReadByte() //Reserved
Me.Planes = r.ReadInt16
Me.BitCount = r.ReadInt16
r.ReadInt32() //Bytes in res
r.ReadInt32() //Image offset
End Sub
End Class
*Note: From the couple of icons i've tested this with, the first entry has dimensions of (0,0). I don't know why, and I can't be sure that all icons have this entry, or that it's always the first. Therefore, I check each one.
ETA: On further investigation, i've found that 0 is used to indicate an icon of size 256.