VB.NET – Get window icons via Windows API

June 4, 2010 — Leave a comment

Well I’ve just spent ages trying to figure out how to get the window icon (the icon displayed in the title bar at the far left) for an external program window from a VB.NET  app – tried using GetClassInfo, GetClassInfoEx, GetClassLong, GetWindowLong and a few other APIs… only to find that you can simply use SendMessage to send the WM_GETICON message and it returns a handle to the icon – and this works perfectly *for most windows* (I’ll explain in a moment). So for anyone else wanting to do the same thing in the future, here’s a basic vb.net example of how to get the window icon from a window.

<DllImportAttribute(“user32.dll”, EntryPoint:=“SendMessageW”)> _
Public Shared Function SendMessage(<InAttribute()> ByVal hWnd As System.IntPtr, ByVal Msg As UInteger, ByVal wParam As UInteger, ByVal lParam As Integer) As IntPtr
End Function

Public Const WM_GETICON As UInteger = &H7F

Public Shared Function GetWindowIcon(ByVal WindowHandle As IntPtr) As Icon
Dim IconHandle As IntPtr = SendMessage(WindowHandle, WM_GETICON, 0, 0)
If Not IconHandle = IntPtr.Zero Then
Return Icon.FromHandle(IconHandle)
Return Nothing
End If
End Function

The reason I say it only works for most windows and not all windows is because there are a couple of applications that seem to ignore the WM_GETICON message (Lotus Notes 7 and Notepad were the two examples I encountered) so it might be worth checking to see if the handle you got from SendMessage is null and if it is then calling GetClassLong and passing GCL_HICON as the second parameter. Using GetClassLong in that way works for Notepad but as of yet I have not been unable to find anything that gets the icon from a Lotus Notes 7 window!

Hope that helps someone out as I know there is currently very little on the internet when you try and find out how to do this from .NET code.

No Comments

Be the first to start the conversation!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s