1. Home
  2. Computing & Technology
  3. Visual Basic

GDI+ Graphics in Visual Basic 2005 .NET
Icons are Images Too!

By Dan Mabbutt, About.com

Mar 10 2007

I mentioned earlier that Icon objects can be thought of as bitmaps too. But Icon objects are handled by the system and they're not Image objects. So if you want to use one in code, you usually have to convert it to a bitmap first. Here's the code to extract the first icon that is saved in an .EXE file and save it in an icon file of it's own. (More than one icon can be stored in a file, but the ExtractAssociatedIcon method will only extract the first one.)

Dim myIconFile As String = "myIcon.ico"
Dim fs As New FileStream(myIconFile, FileMode.CreateNew)
Dim myIcon As Icon
myIcon = Icon.ExtractAssociatedIcon( _
   "C:\WINDOWS\EXEORDLL.EXE")
Dim myIconImage As Bitmap = _
   myIcon.ToBitmap
PictureBox.Image = myIconImage
myIcon.Save(fs)
fs.Close()

--------
Click Here to display the illustration
Click the Back button on your browser to return
--------

The example above shows how to extract and use an icon that someone else has created and added to an executable file, but what if you want to create an icon from a JPG or GIF? There are actually utilities, that you can pay money for out there on the web, to do that. But it's not too hard to simply create your own icons using VB.NET code. Here's an example of the code necessary to create an icon from the Zion.jpg file we have been using.

Dim myBitmap As New Bitmap("C:\zion.jpg")
Dim HIcon As IntPtr = myBitmap.GetHicon()
Dim newIcon As Icon = _
   System.Drawing.Icon.FromHandle(HIcon)
Dim myIconFile As String = "Zion.ico"
Dim fs As New FileStream( _
   myIconFile, FileMode.CreateNew)
newIcon.Save(fs)
fs.Close()

Just to prove that it works, you can assign the icon to the form with a statement like this (put it in the Load event).

Me.Icon = newIcon

And to make sure that you don't miss it, I pointed it out with more GDI+ graphics.

Dim g As Graphics = Me.CreateGraphics
Dim p As Pen = New Pen(Color.Black, 3)
p.EndCap = Drawing2D.LineCap.ArrowAnchor
g.DrawLine(p, 50, 50, 20, 15)
Dim myFont As New Font("Bodoni MT Black", 12)
g.DrawString( _
   "Check out the Zion icon in the corner!!", _
   myFont, Brushes.Red, 55, 60)

--------
Click Here to display the illustration
Click the Back button on your browser to return
--------

Explore Visual Basic
By Category
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Visual Basic
  4. Using VB.NET
  5. GDI+ Graphics in Visual Basic 2005 .NET

©2009 About.com, a part of The New York Times Company.

All rights reserved.