Using an icon on a dialog box window C++ Win32 API

10,026

Solution 1

Use LoadIcon and pass an icon handle to WM_SETICON.

HICON hicon = LoadImageW(GetModuleHandleW(NULL), MAKEINTRESOURCEW(IDI_ICONMAIN), IMAGE_ICON, 0, 0, LR_DEFAULTCOLOR | LR_DEFAULTSIZE);
SendMessageW(hwnd, WM_SETICON, ICON_BIG, hicon);

Solution 2

I had to cast the return value of LoadImageW() to HICON , to avoid the error :

" a value of type "HANDLE" cannot be assigned to an entity of type "HICON" ...."

this worked for me :

.... 
//hDlg is the handle to my dialog window
case WM_INITDIALOG:
    {
        HICON hIcon;

        hIcon = (HICON)LoadImageW(GetModuleHandleW(NULL),
            MAKEINTRESOURCEW(IDI_ICON1),
            IMAGE_ICON,
            GetSystemMetrics(SM_CXSMICON),
            GetSystemMetrics(SM_CYSMICON),
            0);
        if (hIcon)
        {
            SendMessage(hDlg, WM_SETICON, ICON_SMALL, (LPARAM)hIcon);
        }
    }
    break;

and here is the result

win32 Dialog icon

FYI: the used icon was downloaded from :

http://www.iconsdb.com/orange-icons/stackoverflow-6-icon.html

Hope that helps !

Share:
10,026
llk
Author by

llk

Updated on August 07, 2022

Comments

  • llk
    llk almost 2 years

    I am trying to create a dialog box with an icon at the top like so.

    icon dialog

    I am using a resource file to load the icon like so.

    IDI_ICON1          ICON           ".\\usb.ico"
    

    I have tried setting the window icon using the following code.

    SendMessage(hwnd, WM_SETICON, ICON_SMALL, (LPARAM)IDI_ICON1);
    SendMessage(hwnd, WM_SETICON, ICON_BIG, (LPARAM)IDI_ICON1);
    

    hwnd is the window. As a result, I get a blue circle that looks just like the loading icon for Windows 7 and Vista. I am almost positive the icon is being loaded correctly as when I look at the task bar, my program has that icon representing my program. If you need the code I am using for the dialog window itself, let me know I will post it. I am using mingw32 C++ compiler on Windows 7. Thanks!

  • llk
    llk over 12 years
    I tried doing HICON t = LoadIcon(NULL, MAKEINTRESOURCE(IDI_ICON1)); SendMessage(hwnd, WM_SETICON, ICON_BIG, (LPARAM)t); without much luck. I don't know how far from correct my code is.
  • K-ballo
    K-ballo over 12 years
    The first parameter to LoadIcon should be the current instance handle. Get it by calling GetModuleHandle( NULL ).