Tutorial 2 – Icons & Cursors
This tutorial is only a small step up from tutorial 1, but I think that it covers an important aspect of developing a polished and professional feeling application.
Now that we have our window it’s time to set the icon in the top left and the cursor used when the mouse is within the window. It’s just 3 lines of code. Instead of using “NULL” for the hCursor, hIcon and hIconsm fields of our WNDCLASSEX struct we use the following:
windowClass.hIcon = LoadIcon(NULL, IDI_ASTERISK); windowClass.hIconSm = LoadIcon(NULL, IDI_ASTERISK); windowClass.hCursor = LoadCursor(NULL, IDC_CROSS);
The LoadIcon function takes as it’s parameters the handle to an instance of the module containing the icon to be loaded and the name of the icon resource to be loaded. In this case we’re using predefined windows icons so we can pass NULL as the hInstance. For now we’ll use the “Asterisk” icon. LoadCursor is pretty much the same except it deals with cursors instead of icons. In this example we’re loading up the crosshair cursor.
Now we should have a window that looks something like this:
If you wanted to use your own Icon (or for that matter cursor) then first off you need to add an Icon resource to your project. Find an Icon that you want to use or create one yourself (I find that the gimp is very useful for that!). Now right click on your project in Visual Studio. Select Add -> Resource. Then in the dialog that pops up click “Import”. Navigate to your icon file and open it. This will add the icon and a resource file into your project.
To use this newly created icon resource you will need to include the resource header file in your code:
Now simply change the WNDCLASSEX struct to use your icons:
windowClass.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON1));
And that’s all there is to it! Now you should have a window that has the icon you chose in the top left looking a little something like this:
One thing to note here is that Visual studio uses the first icon in your resource script as the icon for the executable. Now that you’ve explicitly added an icon you should notice that your executable uses that icon now too: