Windows Resources

 

Overview

A resource is a text file that allows the compiler to manage such objects as pictures, sounds, mouse cursors, dialog boxes, etc. Microsoft Visual C++ makes creating a resource file particularly easy by providing the necessary tools in the same environment used to program, meaning you usually do not have to use an external application to create or configure this file.

Although an application can use various resources that behave independently of each other, these resources are grouped into a text file that has the .rc extension. You can create this file manually and fill out all necessary parts but it is advantageous to let Visual C++ created it for you. To do this, you add or create one resource at a time when designing it. After saving a resource, it is automatically added to the .rc file. To make your resource recognizable to the other files of the program, you must also create a header file usually called resource.h. This header file must provide a constant integer that identifies each resource and makes it available to any part that needs it. This also means that most, if not all, of your resources will be represented by an identifier.

An identifier is a constant integer whose name usually starts with ID. Although in Win32 programming you usually can use the name of a resource as a string, in MFC applications, resources are usually referred to by their identifier. To make an identifier name (considered a string) recognizable to an MFC (or Win32) function, you use a macro called MAKEINTRESOURCE. Its syntax is:

LPTSTR MAKEINTRESOURCE(WORD IDentifier);

This macro takes the identifier of the resource and returns a string that is given to the function that called it.

In the strict sense, after creating the resource file, it must be compiled to create a new file that has the extension .res. Fortunately, Visual C++ automatically compiles the file and links it to the application so that your efforts are reduced.

Practical Learning: Creating an Application

  1. Start Microsoft Visual Studio or Microsoft Visual C++
  2. Create a new Win32 Project named Resources and located in C:\Programs\MSVC Exercises
     
  3. Click OK and specify the Windows Application as an Empty Project
     
  4. Click Finish
  5. In the Solution Explorer, Resource View, or Class View, right-click the Resources node and click Properties
     
  6. Specify that you want to use MFC as a Shared DLL for your application and click OK
  7. Add a new item as a C++ file and name it Exercise
  8. Change its content as follows:
     
    #include <afxwin.h>
    
    class CResFrame : public CFrameWnd
    {
    public:
    	CResFrame()
    	{
    		Create(NULL, "Resources Fundamentals", WS_OVERLAPPEDWINDOW,
    		       CRect(200, 120, 640, 400), NULL);
    	}
    };
    
    class CResApp: public CWinApp
    {
    public:
    	BOOL InitInstance()
    	{
    		m_pMainWnd = new CResFrame;
    		m_pMainWnd->ShowWindow(SW_SHOW);
    		m_pMainWnd->UpdateWindow();
    
    		return TRUE;
    	}
    };
    
    CResApp theApp;
  9. Test the application
  10. After viewing the result, close it and return to MSVC

Creating Resources

Because resources are different entities, they are created one at a time. They can also be imported from existing files. Most resources are created by selecting the desired one from the Add Resource dialog box

The Add Resource dialog box provides an extensive list of resources to accommodate almost any need. Still, if you do not see a resource you need and know you can use it, you can add it manually to the .rc file before executing the program.

 

Overview of Icons

An icon is a small picture used on a window. It is used in two main scenarios. On a window's frame, it display on the left side of the window name on the title bar. In Windows Explorer, on the Desktop, in My Computer, or in the Control Panel windows, an icon is used to represent an application:

 

 

On a window, the icon is a 16x16 pixels size of picture to accommodate the standard height of the title bar. In window displays such as Windows Explorer or My Computer, the applications can be represented as tiles or as a list. Each display uses a different size of icon. Therefore, an icon is created in two sizes that share the same name but the operating system can manage that concept. This means that you will sometimes create two designs for one icon, a 16x16 pixel and a 32x32 pixel.

An icon is a graphical object made of two categories of colors. One category represents the artistic side of the design. The other is the color that would be used as background so that if the icon is positioned on top of another picture, the background color would be used as the transparent color to show the sections that are not strictly part of the icon. In reality, Microsoft Windows imposes the color that is used as background on an icon. You will find what the icon is.

Icon Design

So far, we were not specifying an icon for our window. Therefore, Visual C++ was using a default icon for the title bar:

This icon is 16x16 pixels. If you want to display a custom icon on the title bar, you can design your own 16x16 pixel icon as a resource.

If you want your application to display a big icon in the thumbnails or tiles views of Windows Explorer or My Computer, design an icon with a 32x32 pixel dimension and using the same name as the 16x16 pixel icon.

To create an icon or add a new one, you can right-click the project name in the Solution Explorer, position the mouse on Add and click Add Resource. This displays the Add Resource dialog box where you can double-click Icon.

To design an icon, you use a set of tools that allow you to draw lines, curves, points, etc. These tools are available from the Graphics toolbar. Each tool is called to by the text of its tool tip. To know the name of a tool, position the mouse on it for a few seconds.

Tool Name Description
Rectangle Selection Used as an outline to select a rectangular area
Irregular Selection Used to draw freehand selection but a rectangle is drawn from the starting selection to the end
Select Color Used to select a color
Erase Used to erase color on an area
Fill Fills a section with a color, only the same pixels with the same color are filled
Magnify Zooms an area of the picture
Pencil Draws lines
Brush Used to draw predefined lines, small squares or large lines
Airbrush Assigns a color to random pixels on the picture
Line Used to draw a line
Curve Draws a curve in a multiple step process
Text Allows drawing text
Rectangle Used to draw a rectangular shape specifying only the border color
Outlined Rectangle Draws a rectangle with one color for the border (pen) and another color for the inside (brush)
Filled Rectangle Used to draw a rectangle filling it with an interior color while the border color is ignored
Round Rectangle Used to draw a round rectangular shape specifying only the border color
Outlined Round Rectangle Draws a round rectangle with one color for the border (pen) and another color for the inside (brush)
Filled Round Rectangle Used to draw a round rectangle filling it with an interior color while the border color is ignored
Ellipse Used to draw an ellipse or a circle
Outlined Ellipse Draws an ellipse or a circle with one color for the border (pen) and another color for the inside (brush)
Filled Ellipse Used to draw an ellipse or a circle filling it with an interior color while the border color is ignored

To use a particular tool, click it to select. Then click on the icon.

 

To design your icon, you can choose colors from the Colors toolbar. Because an icon uses a background color, the default is set as green. The default icon is represented by a small monitor icon.

To use a color, first select a tool on the Graphics toolbar, then click the desired color and draw.

After creating an icon, you can use it for your application. There are two solutions you can use. The default icon used by MSVC is called AFX_IDI_STD_FRAME. Therefore, after designing your icon, you can simply set its name as this default.

 

Introduction to Menus

A menu is a list of actions the user can perform on an application. Each item of the list is primarily a word or a group of words on a line. Different menu items are used for different reasons. For example, some menu items simply display a word or a group of words. Some other items display a check mark. This indicates that the item toggles the availability or disappearance of an object.

When a menu item is only meant to lead to a sub-menu, such a menu item is call a popup menu. There are two types of popup menus. If the menu displays on top of a window, which is the type of menu under the title bar, the word on top, which represents a category of menu, is a popup menu. If a menu item is equipped with an arrow in its right , which means the menu item has a submenu, such a menu item is also a popup menu. Popup menus are used only to represent a submenu. No inherent action is produced by clicking them, except that, when placed on top, such menu items allow opening the submenu.

To create menus that belong to a group, menu items are separated by a horizontal line called a separator. Separators are created differently in MSVC 6 and MSVC .Net.

There are two primary types of menus in most applications: a main menu and a popup menu.

The Main Menu

A menu is considered a main menu, when it carries most or all of the actions the user can perform on an application. Such a menu is positioned on the top section of the main window in which it is used. A main menu is divided in categories of items and each category is represented by a word. Here is an example:

On the Visual Studio IDE, the categories of menus are File, Edit, View, Project, etc. To use a menu, the user first clicks one of the words that displays on top. Upon clicking, the menu expands and displays a list of items that belong to that category. Here is an example where the View menu of WordPerfect was clicked therefore got expanded:

There is no strict rule on how a menu is organized. There are only suggestions. For example, actions that are related to file processing, such as creating a new file, opening an existing file, saving a file, printing the open file, or closing the file usually stay under a category called File. In the same way, actions related to viewing things can be listed under a View menu.

Main Menu Design

There are two ways you can create a main menu. You can use the Win32 approach in which case you would create or open your .rc file and create a section as follows:

IDR_MAINFRAME MENU
BEGIN
    POPUP "&File"
    BEGIN
        MENUITEM "&New",        IDM_FILENEW
        MENUITEM "&Open",       IDM_FILEOPEN
        MENUITEM SEPARATOR
        MENUITEM "E&xit",       IDM_FILEEXIT
    END
    POPUP "&Help"
    BEGIN
        MENUITEM "&About",      IDM_HELPABOUT
    END
END

If you create your file manually, you must also remember to create or edit the resource.h file in order to specify an identifier for each menu. The alternative, which we will use, is to "visually" create the menu in Visual Studio. When doing this, the studio itself would update the resource.h as items are added or removed.

To create a menu, first add a resource of type Menu. To create a popup menu that would display on top of the main menu, click the item on top and type the desired string in the Caption field of the Properties window. Such a popup menu item would not use a specify identifier.

To create a menu item, click the line under the popup menu, provide an identifier and a caption.

To create popup menu that would display an arrow, in MSVC 6, click the menu item and click the Pop-up check box. In MSVC .Net, the arrow for the popup menu is readily available so you can use or ignore it.

Practical Learning: Creating a Main Menu

  1. On the main menu of MSVC 6, click Insert -> Resource...
    On the main menu of MSVC .Net, click Project -> Add Resource...
  2. On the Add Resource dialog box, double-click Menu
  3. In the Resource View, click IDR_MENU1 to select it and change its identifier to IDR_MENU_RES
  4. In the main window, click the top box (in MSVC .Net, it displays Type Here), type Family and press Enter
  5. Click the item under Family. Type Father and press Enter.
  6. Type Mother and press Enter
     
  7. To add a separator, in MSVC 6, right-click the item under Mother and click Properties. On the Properties window, click the Separator check box.
    In MSVC .Net, click the item under mother, type - and press Enter
  8. Complete the menu as follows (remember to add the lower separator):
     
  9. To move the Grand-Child item and position it under the lower separator, click and hold the mouse on Grand-Child, then drag in the bottom direction until the selection is in the desired position:
     
  10. Release the mouse.
  11. To create another main menu item, click the box on the right side of Family, type Category and press Enter
  12. Click the item under Category, type Parent and press Enter.
  13. Type Child and press Enter
  14. To move the Category menu and position it to the left side of Family, click and drag Category in the left direction
     
  15. When it is positioned to the left of Family, release the mouse. Notice that the popup menu and its submenus moved.
  16. To create a new main menu item, click the box on the right side of Family, type Job Functions and press Enter
  17. Click the box under Job Functions and type Level
  18. While Level is still selected, on the Properties window of MSVC 6, click the Pop-up check box.
    While Level is still selected, in MSVC 7, click the box on the right side of Level
  19. Type Executive and press Enter
  20. Complete the popup menu as follows:
     
  21. To use the new menu, open the Exercise.cpp file and change the CFrameWnd::Create() method as follows:
     
    class CResFrame : public CFrameWnd
    {
    public:
    	CResFrame()
    	{
    		Create(NULL, "Resources Fundamentals", WS_OVERLAPPEDWINDOW,
    			   CRect(200, 120, 640, 400), NULL,
    			   MAKEINTRESOURCE(IDR_MENU_RES));
    	}
    };
  22. Test the application
     
  23. Close the window and return to MSVC
 

Introduction to Toolbars

A toolbar is a Windows control that allows the user the perform some actions on a form by clicking a button instead of using a menu. A toolbar provides a convenient group of buttons that simplifies the user's job by bringing the most accessible actions as buttons so that, instead of performing various steps to access a menu, a button on a toolbar can bring such common actions closer to the user.

Toolbars usually display under the main menu. They can be equipped with buttons but sometimes their buttons or some of their buttons have a caption. Toolbars can also be equipped with other types of controls

Creating a Toolbar

To create a toolbar, from the Add Resource dialog box, click Toolbar and click New.

A toolbar is only a container and does not provide much role by itself. To make a toolbar efficient, you should equip it with the necessary controls.

The most common control used on a toolbar is a button. After adding a new toolbar, it is equipped with a gray button. You can simply start designing that button as you see fit. Once you start design it. Once you start designing a button, a new one is added. You can keep designing the buttons until you get as many buttons as you need. If you design a button but do not need it anymore, to delete it, drag it away from the toolbar. The space between two buttons is called a separator. To put a separator between two buttons, drag one away from the other just a little.

A toolbar can be equipped with various types of controls.

 

Introduction to Accelerators

An access key is a letter that allows the user to perform a menu action faster by using the keyboard instead of the mouse. This is usually faster because the user would not need to position the mouse anywhere, which reduces the time it takes to perform the action.

The most basic accelerator keys allow the user to access each item of the menu with a key. To do this, the user must first give focus to the menu. This is done by press the F10 function key or Alt. Once the menu has focus, you can provide a unique letter that the user can press to active the menu. Each main popup menu must have a unique letter that serves as access key. The letter is underlined to show that it the access key for that particular menu.

As a suggestion, when creating the access keys, use the first letter of the menu item, as in File, Edit, or View. If you have another menu item that starts with a letter already used, as Format after File, use the next letter that has not been used already. This can result in File, Edit, View, F&ormat, Insert, Efficiency. Only in the same category should follow this rule. The menu items under a popup menu use access keys that are independent of another category. This means that, under File, you can use a submenu that uses the letter E as access key even though Edit on top is using it.

To use access keys, the user press F10 or Alt and presses the underlined letter, which opens the menu category. Then the user can click the desired underlined letter in the displayed list.

To create an access key, type an ampersand "&" on the left of the menu item.

Practical Learning: Creating Access Keys

  1. In the Resource View, double-click the identifier of the menu to display the menu.
    Right-click Category and click Properties
  2. In the Caption box, click to left of Category, type & and press Enter
  3. Complete the menu with the following captions:
     
    &Category &Family &Job Functions
    &Parent &Father &Level
    &Child &Mother &Executive
    &Son &Senior
    &Daughter &Junior
    &Grand-child &Assistant
  4. Test the application and return to MSVC

Shortcuts

A shortcut key is a key or a combination of keys the user presses to perform an action that would otherwise be done on a menu item. Most shortcuts are made of the Ctrl key simultaneously pressed with a letter key. Examples are Ctrl + N, Ctrl + O, or Ctrl + D. Some applications, such as Adobe Photoshop or Macromedia Flash, use a shortcut made of only one key.

To create a shortcut, on the right side of the string that makes up a menu caption, type \t followed by the desired combination.

Practical Learning: Creating Shortcut Keys

  1. In the Resource View, click Category, right-click Parent, and click Properties
  2. In the Caption box, click to right side of Parent, type \tCtrl+R
     
  3. In the same way, set the shortcut of Child to Ctrl+D
     
     
  4. Test the application and return to MSVC

Accelerator Table

An Accelerator table is a list of items where each item of the table combines an identifier, a (shortcut) key, and a constant number that specifies the kind of accelerator key. Each item is a variable of the ACCEL class whose syntax is:

typedef struct tagACCEL { 
    BYTE   fVirt; 
    WORD   key; 
    WORD   cmd; 
} ACCEL, *LPACCEL;

Using a variable or variables of type ACCEL, you can create as many items as needed. Then declare an HACCEL variable. HACCEL is a handle to a ACCEL and is used to pass the ACCEL table to the program. This would allow the compiler to translate the items of the accelerator to keys that the program can use.

Just like the other resources, an accelerator table can be created manually in a .rc file but MSVC simplifies the process by allowing you to "visually" create the table.

Practical Learning: Creating an Accelerator Table

  1. On the main menu of Visual Studio, click Insert -> Resource... or Project -> Add Resource...
  2. In the Add Resource dialog box, double-click Accelerator
  3. In the Properties window, click the arrow of the ID combo box and select ID_CATEGORY_PARENT
  4. Click the Key box and type R
  5. Make sure the Ctrl check box is checked or that the Ctrl field is set to True. Also, make sure the Type is set to VIRTKEY or CirtKey
     
  6. In the same way, create an accelerator item for the Child menu:
     
  7. To use the accelerator, change the program as follows:
     
    class CResFrame : public CFrameWnd
    {
    public:
    	HACCEL m_hAccel;
    
    	CResFrame()
    	{
    		m_hAccel = ::LoadAccelerators(AfxGetInstanceHandle(),
    		MAKEINTRESOURCE (IDR_ACCELTEST));
    
    		Create(NULL, "Resources Fundamentals", WS_OVERLAPPEDWINDOW,
    			   CRect(200, 120, 640, 400), NULL, MAKEINTRESOURCE(IDR_TEST));
    	}
    };
  8. Test the application and return to MSVC
 

Version Information Overview

The version of a computer program allows to have some information about the product such as it official name, a release number, the person or company that owns its copyright, the year of the current release, etc.

To create the pieces of information that make up the version information, you can use the Version Information Editor.

Practical Learning: Creating Version Information

  1. On the main menu of MSVC, click Insert -> Resource... or Project -> Add Resource
  2. In the Add Resource dialog box, click Version and click New. Notice that a complete file is generated for you
  3. To change the first key, double-click the top 1, 0, 0, 1 and edit it to display 1, 3, 1, 1
  4. Double-click PRODUCTVERSION and type 1, 2, 2, 3
  5. Double-click Comments and type This program is primarily intended as an introduction to Windows resources
  6. To add a new string, right-click in the window and click New Version Info Block
     
  7. Save All
 

Introduction to Cursors

 A cursor is a small picture that represents the position of the mouse on a Windows object. Because Windows is a graphic intensive operating system, when it installs, it creates a set of standard or regularly used cursors. These can be seen by opening the Control Panel window and double-clicking the Mouse icon. This opens the Mouse Properties dialog box where you can click the Pointers tab to see a list of standard cursors installed by Windows:

Mouse Properties

Creating and Using Cursors

Microsoft Windows installs a wide array of cursors for various occasions. Like all other resources, a cursor is identified by a constant integer that can be communicated to other files that need it. 

Essentially, a cursor uses only two colors, black or white. This is because a cursor is only used as an indicator of the presence or position of the mouse pointer on the screen. Based on this (limitation), you ought to be creative. The minimum you can give a cursor is a shape. This can be a square, a rectangle, a circle, an ellipse, a triangle, or any shape of your choice. You can make the cursor fully black by painting it with that color. If you decide to make the cursor completely white, make sure you draw the borders of the cursor.

Between the black and white colors, two gray degrees are provided to you. In reality these two colors are used to give a transparency to the cursor so the background can be seen when the mouse passes over a section of the document.

After designing a cursor, you should define its hot spot. A cursor's hot spot is the point that would be used to touch the specific point that the mouse must touch to perform the action expected on the mouse. The hot spot must be an area, namely a spot, on the cursor but it could be anywhere on that cursor. You should specify the hot spot in the most intuitive section of the cursor. In other words, the user should easily identify it since it is not otherwise visible.

If you do not want to show a cursor, you can use the Wind32 API ShowCursor() function. Its syntax is:

int ShowCursor(BOOL bShow);

To hide a cursor, specify the argument as FALSE.

Practical Learning Practical Learning: Creating a Cursor

  1. To create a new cursor, on the main menu, either click Insert -> Resource... or click Project -> Add Resource
  2. In the Insert Resource or Add Resource dialog box, click Cursor and click New
  3. In the Resource View, right-click the name of the cursor and click Properties.
  4. Change its ID to IDC_APP_CURS and its Filename to appcurs.cur
  5. On the Toolbox, click the Line tool and select the black color
  6. Design the cursor as follows:
     
  7. To define the hot spot, on the toolbar of the editor, click the Set Hot Spot button or . Click the middle of the square:
     
  8. Save All
  9. Close the Cursor Properties window.
 

String Tables

A string table is a list of all object strings that are part of an application. It allows any part of the program to refer to that table when a common string is needed. The advantage of a string table is that it can be used as a central place when to store or retrieve strings that any other objects of the application may need. These can include the titles or captions of Windows controls, the formatting strings used inside of functions or controls.

Creating and Using a String Table

When you install Microsoft Visual C++, it also installs a lot of strings that are readily available for your applications. We will review these strings as we move on. Most of the time, you will also need to create additional or your own strings. To create a string table, from the Add Resource dialog box, click String Table and click New. Each item of the table is made of three sections: an identifier, a constant natural number, and a caption. To add a new item, you can right-click in the String Table window and click New String. You can also double-click the last empty row in the window. You can also press Insert. Either case, the String Properties window would display:

You can either type a new ID or select an existing ID from the ID combo box. Then type the associated string in the Caption box. Continually, you would have created a String Table:

The identifier, ID, is the same type of ID used when creating the resources earlier. In fact, most of the IDs used on a string table are shared among resources, as we will learn when reviewing the CFrameWnd::LoadFrame() method. The value column contains a constant LONG integer for each identifier. You will not need to specify this number when using the String Table window; Visual C++ automatically and independently creates and manages those numbers. If you want to create a string and specify your own number, on the main menu of MSVC 6, you can click View -> Resource Symbols...

In the Resource Symbols window, to create a new string, click the New... button to display the New Symbol dialog box:

You can then type an IDentifier in the Name edit box and the desired number in the Value edit box. Over all, you should only use numbers between 101 and 127 and avoid numbers over 57344.

To edit an item from the String Table window, double-click the row needed to display the String Properties window with the selected item.

 

Window Registration and Standard Resources

The CFrameWnd::Create() method we have used so far provides a quick mechanism to create a window. Unfortunately, it is not equipped to recognize custom resources. In reality, this method is only used to create a window, not to receive resources. As we saw in its syntax, its first argument, lpszClassName is used to get a window that has been built, that is, a window whose resources have been specified. If you do not specify these resources, that is, if you pass the lpszClassName argument as NULL, the compiler would use internal default values for the window. These default are: a window that can be redrawn when the user moves or resizes it, a white background for the main area of the window, the arrow cursor, and the Windows "flat" icon, called IDI_APPLICATION.

To use your own resources, you must first create then register them. To register the resources, you can call the AfxRegisterWndClass() global function. Its syntax is:

LPCTSTR AFXAPI AfxRegisterWndClass(UINT nClassStyle,
                                   HCURSOR hCursor = 0,
                                   HBRUSH hbrBackground = 0,
                                   HICON hIcon = 0);

As you can see, this function is used to register, the window style, a cursor, a color for the background, and an icon. Only the window style is required. After registering the window's style or the style and the resources, this function returns a (constant) string that can be passed as the first argument of the CFrameWnd::Create() method.

Practical Learning Practical Learning: Using Standard Resources

  1. To use the AfxRegisterWndClass() function with default values, change the Exercise.cpp file as follows:
     
    class CResFrame : public CFrameWnd
    {
    public:
        CResFrame()
        {
    	const char *RWC = AfxRegisterWndClass(NULL, NULL,
                                                   (HBRUSH)::GetStockObject(WHITE_BRUSH),
                                                   NULL);
    	Create(RWC, "Resources Fundamentals", WS_OVERLAPPEDWINDOW,
    			   CRect(200, 120, 640, 400), NULL);
        }
    };
  2. Test the application
  3. After viewing the window, close it and return to MSVC
  4. To use a standard cursor and a standard icon, change the Exercise.cpp file as follows:
     
    CResFrame()
    {
        HCURSOR hCursor;
        HICON hIcon;
      
        hCursor = AfxGetApp()->LoadStandardCursor(IDC_SIZEALL);
        hIcon   = AfxGetApp()->LoadStandardIcon(IDI_EXCLAMATION);
    
        const char *RWC = AfxRegisterWndClass(CS_VREDRAW | CS_HREDRAW,
    	                                 hCursor,
    				     (HBRUSH)GetStockObject(BLACK_BRUSH),
                                              hIcon);
        Create(RWC, "Resources Fundamentals", WS_OVERLAPPEDWINDOW,
               CRect(200, 120, 640, 400), NULL);
    }
  5. Test the application
     
    Window with custom resources
  6. After viewing the window, close it and return to MSVC

Window Registration and Custom Resources

If the standard cursors and/or icons are not enough, you can create your own. To create your own cursor, display and select Cursor from the Add Resource dialog box. A starting but empty cursor would be displayed. Design the cursor to your liking.

To use a custom cursor, you can retrieve its identifier and pass it to the CWinApp::LoadCursor() method. It is overloaded as follows:

HCURSOR LoadCursor(LPCTSTR lpszResourceName) const;
HCURSOR LoadCursor(UINT nIDResource) const;

To use a custom icon, you can pass its identifier to the CWinApp::LoadIcon() method overloaded as follows:

HICON LoadIcon(LPCTSTR lpszResourceName) const;
HICON LoadIcon(UINT nIDResource) const;

When calling one of these methods, you can simply pass its identifier as argument. You can also specify the resource identifier as a constant string. To do this, pass the name of the icon to the MAKEINTRESOURCE macro that would convert its identifier to a string.

Practical Learning Practical Learning: Using Custom Resources

  1. To use a custom cursor and a custom icon, change the Exercise.cpp file as follows:
     
    #include <afxwin.h>
    #include "resource.h"
    
    class CResFrame : public CFrameWnd
    {
    public:
        CResFrame()
        {
    	HCURSOR hCursor;
    	HICON hIcon;
      
    	hCursor = AfxGetApp()->LoadCursor(IDC_APP_CURS);
    	hIcon   = AfxGetApp()->LoadIcon(IDI_APP_ICO);
    
    	const char *RWC = AfxRegisterWndClass(CS_VREDRAW | CS_HREDRAW,
    					  hCursor,
    					  (HBRUSH)GetStockObject(BLACK_BRUSH),
    					  hIcon);
    	Create(RWC, "Custom Resources", WS_OVERLAPPEDWINDOW,
    		   CRect(200, 120, 640, 400), NULL);
        }
    };
    
    class CResApp: public CWinApp
    {
    public:
        BOOL InitInstance()
        {
    	m_pMainWnd = new CResFrame;
    	m_pMainWnd->ShowWindow(SW_SHOW);
    	m_pMainWnd->UpdateWindow();
    
    	return TRUE;
        }
    };
    
    CResApp theApp;
  2. Test the application:
     
    Windows Custom Resources
  3. After viewing the window, close it and return to MSVC.

Frame Loading

So far, in order to create a window, we learned to use the CFrameWnd::Create() method. Because that method does not recognize resources, we resolved to use the AfxRegisterWndClass() function to register the necessary resources before calling the CFrameWnd::Create() method. The MFC provides another, simpler, technique to create a window. This is done using the CFrameWnd::LoadFrame() method.

To create a window with one simple call, first create the necessary resources, namely an accelerator table, a menu, an icon, a string table (and possible a toolbar, as we will learn). The only rule to follow is that all of these resources must have the same name. As a habit, the common name used for resources is IDR_MAINFRAME.

The syntax of the LoadFrame() method is:

BOOL LoadFrame(UINT nIDResource,
               DWORD dwDefaultStyle = WS_OVERLAPPEDWINDOW | FWS_ADDTOTITLE,
               CWnd* pParentWnd = NULL,
               CCreateContext* pContext = NULL );

The only required argument to the LoadFrame() method is the identifier shared by the resources. Like the Create() method, you can use LoadFrame() to specify the style of the window. Its characteristics are specified as the dwDefaultStyle argument. If this window has a parent, you can specify it using the pParentWnd argument.

Practical Learning Practical Learning: Loading a Frame

  1. Create a new project named Frame Loader and stored in C:\Programs\MSVC Exercises
    Make sure you create it as a Windows Application with an Empty Project
  2. Access the application's settings or properties and specify that you want to use MFC As A Shared DLL
  3. Add a new menu resource as follows:
     
  4. Change the ID of the menu from IDR_MENU1 to IDR_MAINFRAME and save the resource as FrmLoad.rc
    If using MSVC 6, add the .rc file to the project (Project -> Add to Project -> File, Form Loader.rc)
  5. Create a new Icon identified as IDR_MAINFRAME and design it as follows:
     
  6. Create a new accelerator table identified as IDR_MAINFRAME as follows:
     
  7. Create a String Table and add a string identified as IDR_MAINFRAME with a Caption as Combined Resources
     
  8. Create a new C++ source file and name it Main
  9. In the Main.cpp file, create the application as follows:
     
    #include <afxwin.h>
    #include "resource.h"
    
    class CMainFrame : public CFrameWnd
    {
    public:
    	CMainFrame ()
    	{
    		LoadFrame(IDR_MAINFRAME);
    	}
    };
    
    class CMainApp: public CWinApp
    {
    public:
    	BOOL InitInstance()
    	{
    		m_pMainWnd = new CMainFrame ;
    		m_pMainWnd->ShowWindow(SW_SHOW);
    		m_pMainWnd->UpdateWindow();
    
    		return TRUE;
    	}
    };
    
    CMainApp theApp;
  10. Test the application.

Previous Copyright © 2003 FunctionX, Inc. Next