Introduction To FileSystemWatcherHow To Compare Files in VB.NET

3 Handy Icon Functions You Can Use

October 2nd, 2007

Icon-bot at your serviceThe System.Drawing.Icon class provides several ways for you to work with icons. In this article we’ll look at using its functions to get the icon for a file, creating an icon from a bitmap file, and converting a bitmap to an icon.

Get the Icon for a File

ExtractAssociatedIcon is a shared function that makes it easy to get the icon for a particular file. It will work with any type of file, not just executables. Here’s what the code looks like:

'
'
Me.Icon = Icon.ExtractAssociatedIcon(fileName)
'
'

In this case we’re setting the form icon to the extracted icon, like you might want to do if you had a MDI child form loading a document.

Another common usage is to load the icon into an ImageList control so that you can use it in a ListView or TreeView control. In the example below we’re assuming that we’re loading the contents of a specified folder into a Listview control.

Dim DirInfo As New DirectoryInfo(txtPath.Text)
For Each LookupFile As FileInfo In DirInfo.GetFiles()
    imlFiles.Images.Add(LookupFile.Name, Icon.ExtractAssociatedIcon(LookupFile.FullName))
    lvwFiles.Items.Add(LookupFile.Name, LookupFile.Name)
Next

Note that we retrieve the icon and load it into our ImageList, then load the ListView and point to our newly loaded image by key.

Creating an Icon from a Bitmap File

Let’s suppose you wanted to create an icon for your form from a bitmap image. How would you do that? The FromHandle method allows us to convert a bitmap into an icon. Here’s how to do it.

Private Sub ChangeIcon(ByVal bitmapFilename As String)
    Using IconBitmap As New Bitmap(bitmapFilename)
        Dim HIcon As IntPtr = IconBitmap.GetHicon()
        Using newIcon As Icon = System.Drawing.Icon.FromHandle(HIcon)
            Me.Icon = newIcon
            DestroyIcon(newIcon.Handle)
        End Using
    End Using
End Sub

<System.Runtime.InteropServices.DllImportAttribute("user32.dll")> _
Private Shared Function DestroyIcon(ByVal handle As IntPtr) As Boolean
End Function

First, we load our bitmap file into a bitmap object and get an icon handle. Next we use the FromHandle function to create a new icon and set it to our form’s icon property. The last function, DestroyIcon, is used to free memory used in this process. DestroyIcon is imported in from user32.dll by using InteropServices. Note that we also have Using blocks since we’re working with unmanaged resources.

Converting a Bitmap File to an Icon File

As you can probably guess, the above method could be used to convert a bitmap file into an icon file. To do this you use the Save method of the icon object. Here’s how it works:

Private Sub BitmapToIcon(ByVal bitmapFilename As String, ByVal iconFilename As String)
    Using BaseBitmap As New Bitmap(bitmapFilename)
        Using IconBitmap As New Bitmap(32, 32)
            Using IconGraphics As Graphics = Graphics.FromImage(IconBitmap)
                IconGraphics.DrawImage(BaseBitmap, 0, 0, IconBitmap.Width, IconBitmap.Height)
                Dim HIcon As IntPtr = IconBitmap.GetHicon()
                Using newIcon As Icon = System.Drawing.Icon.FromHandle(HIcon)
                    Using IconStream As New System.IO.FileStream(iconFilename, FileMode.Create)
                        newIcon.Save(IconStream)
                    End Using
                    DestroyIcon(newIcon.Handle)
                End Using
            End Using
        End Using
    End Using
End Sub

The tricky part here is that we need to size the source bitmap to standard icon size, 32×32 pixels. So, to do this, we create a new bitmap and draw the source bitmap to it. We get the icon handle, create a new icon, then create a FileStream with our destination file name, and save the new icon. Once again, we’re using the DestroyIcon function and Using blocks to insure we release resources correctly.

Note that this method isn’t quite complete since it only works with one size of icon (32×32) with 16 colors. More work is needed to have it support more icon formats.

That’s our 3 examples. As I mentioned, they’re just the basics and you will want to work them into your application seamlessly. I don’t recommend just cutting and pasting them in. Take the time to integrate them into your app.

Let me know if you have any questions or suggestions about these routines by leaving me a comment.

Share This Article: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Reddit
  • StumbleUpon
  • Technorati
  • DotNetKicks
  • DZone

Entry Filed under: Code Examples


Rate This Article:

Not That GoodCould Be BetterOKGoodGreat (No Ratings Yet)
Loading ... Loading ...

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed


Visit Me At My New Site, Programming In C#

Most Popular Articles

Highest Rated Articles

Categories

Most Recent Articles

Feeds

 Subscribe in a reader

To subscribe by e-mail
Enter your address here

Delivered by FeedBurner

VB Opportunities

Archives