Display Icon on form in vb.net

MaQleod picture MaQleod · May 27, 2009 · Viewed 19.7k times · Source

How would I display an Icon at 48x48 resolution on a form in vb.net? I looked at using imagelist , but I don't know how to display the image that I add to the list using code and how to specify it's coordinates on the form. I did some google searching but none of the examples really show what I need to know.

Answer

Fredrik Mörk picture Fredrik Mörk · May 27, 2009

The ImageList is not ideal when you have image formats supporting alpha transparency (at least it this used to be the case; I didn't use them a lot recently), so you are probably better off loading the icon from a file on disk or from a resource. If you load it from disk you can use this approach:

' Function for loading the icon from disk in 48x48 size '
Private Function LoadIconFromFile(ByVal fileName As String) As Icon
    Return New Icon(fileName, New Size(48, 48))
End Function

' code for loading the icon into a PictureBox '
Dim theIcon As Icon = LoadIconFromFile("C:\path\file.ico")
pbIcon.Image = theIcon.ToBitmap()
theIcon.Dispose()

' code for drawing the icon on the form, at x=20, y=20 '
Dim g As Graphics = Me.CreateGraphics()
Dim theIcon As Icon = LoadIconFromFile("C:\path\file.ico")
g.DrawIcon(theIcon, 20, 20)
g.Dispose()
theIcon.Dispose()

Update: if you instead want to have the icon as an embedded resource in your assembly, you can alter the LoadIconFromFile method so that it looks like this instead:

Private Function LoadIconFromFile(ByVal fileName As String) As Icon
    Dim result As Icon
    Dim assembly As System.Reflection.Assembly = Me.GetType().Assembly
    Dim stream As System.IO.Stream = assembly.GetManifestResourceStream((assembly.GetName().Name & ".file.ico"))
    result = New Icon(stream, New Size(48, 48))
    stream.Dispose()
    Return result
End Function