Using Icons in Your Program

Icons have only a couple of purposes. Most Windows programs use an icon only for displaying the program in the icon area. This is accomplished when defining the window class:

wndclass.hIcon = LoadIcon (hInstance, "myicon") ;

If you later want to change the program's icon, you can do so using SetClassWord. Let's assume you had a second icon in your resource script:

anothericon ICON iconfil2.ico

You can substitute this icon for "myicon" with the statement:

SetClassWord (hwnd, GCW_HICON, LoadIcon (hInstance,"anothericon")) ;

If you save the icon handle from a LoadIcon call, you can also draw the icon on the client area of your window:

DrawIcon (hdc, x, y, hIcon) ;

Windows itself uses the DrawIcon function when displaying your program's icon in the icon area. Windows obtains the handle to the icon from the window class structure. You can obtain the handle in the same way:

DrawIcon (hdc, x, y, GetClassWord (hwnd, GGW_HICON)) ;

The RESOURC1 sample program uses the same icon for the window class and for displaying in its client area. In the resource script the icon is given the same name as the program:

resourc1 ICON resourc1.ico

Because the character string "Resourc1" is stored in the array szAppName and is already used in the program for the window class name, the LoadIcon call is simply:

LoadIcon (hInstance, szAppName) ;

You'll notice that LoadIcon is called twice in RESOURC1 for the same icon, once when defining the window class in WinMain and again when obtaining a handle to the icon while processing the WM_CREATE message in WndProc. Calling LoadIcon twice presents no problem: Both calls return the same handle. Windows actually loads the icon only once from the .EXE file and then uses it for all instances of the RESOURC1 program.