Question How do I extract a 48x48 icon from an exe?

ikantspelwurdz

Well-known member
Joined
Dec 8, 2009
Messages
49
Programming Experience
1-3
Using the function Icon.ExtractAssociatedIcon seems to only retrieve 32x32 icons, and if the target exe file only contains 48x48, then it seems to squash it down to 32x32 before returning an icon.

So, I did some googling, and found what looked like a solution. I wrote up this code:

VB.NET:
Imports System.IO
Imports System.Runtime.InteropServices

Public Class Form1

    Private Const SHGFI_ICON As Integer = &H100
    Private Const SHGFI_SMALLICON As Integer = &H1
    Private Const SHGFI_LARGEICON As Integer = &H0

    Public Structure SHFILEINFO
        Public hIcon As IntPtr
        Public iIcon As Integer
        Public dwAttributes As Integer
        <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=256)> Public szDisplayName As String
        <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=80)> Public szTypeName As String
    End Structure

    Public Declare Auto Function SHGetFileInfo Lib "shell32.dll" ( _
        ByVal pszPath As String, _
        ByVal dwFileAttributes As FileAttributes, _
        ByRef psfi As SHFILEINFO, _
        ByVal cbFileInfo As UInt32, _
        ByVal uFlags As UInt32) As IntPtr

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        Dim sFile As String = "..\..\braid.exe"
        Dim hImgLarge As IntPtr
        Dim shinfo As New SHFILEINFO
        Dim myIcon As System.Drawing.Icon

        hImgLarge = SHGetFileInfo(sFile, 0, shinfo, _
                    Marshal.SizeOf(shinfo), _
                    SHGFI_ICON Or SHGFI_LARGEICON)
        myIcon = System.Drawing.Icon.FromHandle(shinfo.hIcon)

        PictureBox1.Image = myIcon.ToBitmap
    End Sub
End Class

But I'm having the exact same problem as before. The result is the 32x32 icon. And yes, the file "braid.exe" does contain a 48x48 icon. It also contains a 128x128, a 32x32, and a 16x16, but I'm only interested in the 48x48.

Also, if I get rid of the SHGFI_ICON flag, leaving only the SHGFI_LARGEICON flag, then running the program throws this exception:
VB.NET:
An unhandled exception of type 'System.ArgumentException' occurred in System.Drawing.dll

Additional information: Win32 handle that was passed to Icon is not valid or is the wrong type.

So, what am I doing wrong? How can I get a 48x48 icon extracted properly?

Also, a ZIP file with the project can be downloaded here:
2shared - download iconex.zip
(click the part that says "Save file to your PC: click here")
 
Back
Top