Attribute VB_Name = "FormIconChanger"
Option Explicit

Private Declare Function GetWindow Lib "user32" ( _
  ByVal hwnd As Long, _
  ByVal wCmd As Long) As Long
  
Private Declare Function SendMessage Lib "user32" _
  Alias "SendMessageA" ( _
  ByVal hwnd As Long, _
  ByVal wMsg As Long, _
  ByVal WParam As Long, _
  ByVal lParam As Long) As Long

Private Const GW_OWNER = 4
Private Const WM_SETICON = &H80

Private Const ICON_SMALL = 0
Private Const ICON_BIG = 1

Private Const SM_CXICON = 11
Private Const SM_CYICON = 12

Private Const SM_CXSMICON = 49
Private Const SM_CYSMICON = 50

Private Const IMAGE_ICON = 1
Private Const LR_SHARED = &H8000&

Public Sub SetFormIcon(ByVal hwnd As Long, ByVal sIconResName As Long)
  Dim cx As Long
  Dim cy As Long
  Dim hIcon As Long
  Dim hwndOwner As Long
  Dim hTemp As Long

  hTemp = hwnd
  Do
    hTemp = GetWindow(hTemp, GW_OWNER)
    If hTemp <> 0 Then hwndOwner = hTemp
  Loop Until hTemp = 0
      
  cx = GetSystemMetrics(SM_CXICON)
  cy = GetSystemMetrics(SM_CYICON)
  hIcon = LoadImage(App.hInstance, sIconResName, IMAGE_ICON, cx, cy, LR_SHARED)
  SendMessage hwnd, WM_SETICON, ICON_BIG, hIcon
  SendMessage hwndOwner, WM_SETICON, ICON_BIG, hIcon
   
  cx = GetSystemMetrics(SM_CXSMICON)
  cy = GetSystemMetrics(SM_CYSMICON)
  hIcon = LoadImage(App.hInstance, sIconResName, IMAGE_ICON, cx, cy, LR_SHARED)
  SendMessage hwnd, WM_SETICON, ICON_SMALL, hIcon
  SendMessage hwndOwner, WM_SETICON, ICON_SMALL, hIcon
End Sub

