How to create a Menu in your application
The images above demonstrate the use of menu in a win32 application. To create Menu you need two file.
In our case they are resource.h and tut6_CreatingMenuItem.rc (files are attached with this post)
tut6_CreatingMenuItem.rc has following contents
- resource.h
- ProgramName.rc
In our case they are resource.h and tut6_CreatingMenuItem.rc (files are attached with this post)
tut6_CreatingMenuItem.rc has following contents
// Microsoft Visual C++ generated resource script.
//
#include "resource.h"
#include "afxres.h"
/////////////////////////////////////////////////////////////////////////////
//
// Menu
//
SAW_MENU1 MENU
BEGIN
POPUP "&Menu"
BEGIN
MENUITEM "&About", ID_ABOUT
MENUITEM "&Exit", ID_EXIT
END
END
//IDI_PROGICON ICON "prog.ico"
resource.h has following contents
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by tut6_CreatingMenuItem.rc
//
#define IDC_STATIC -1
#define SAW_MENU1 40101
#define ID_ABOUT 40102
#define ID_EXIT 40103In your main program tut6_CreatingMenuItem.cpp add the following line in top of your program.
#include "resource.h"Now add the rc file in your program as shown in images below.
And change this line in your program
wcex.lpszMenuName = NULL;
to
to
wcex.lpszMenuName = MAKEINTRESOURCE(SAW_MENU1);
How to take action when a Menu item is clicked
When a menu item is clicked application receives a WM_COMMAND message. Hence we have to handle this message to perform necessary actions.
Add these lines in your callback function
Add these lines in your callback function
case WM_COMMAND:
switch(LOWORD (wParam)) {
case ID_ABOUT:
MessageBox(hWnd, "Tutorial 6: Working with menu and icons",
"SA-OS Win32 Tutorial", MB_OK | MB_ICONINFORMATION);
break;
case ID_EXIT:
PostMessage(hWnd, WM_CLOSE, 0, 0);
break;
default:
break;
}
break;
Posting WM_CLOSE message in message queue closes the application.
How to set an icon for your windows application
You have to use 16x16 or 32x32 icon file to make this work. In our case it is prog.ico
SAW_PROGICON ICON "prog.ico"
Add the following in resource.h
#define SAW_PROGICON 40104
And change this line in your WinMain function
- Add the following line in tut6_CreatingMenuItem.rc
SAW_PROGICON ICON "prog.ico"
#define SAW_PROGICON 40104
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_APPLICATION));
to
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(SAW_PROGICON));
to
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(SAW_PROGICON));
Build the program and run again.
How to disable/gray a Menu Item
To disable or make a Menu item gray add following lines in your code where necessary
HMENU hmenu = GetMenu(hwnd); // hwnd is the handle of the window containing the menu
EnableMenuItem(hmenu, ID_EXIT, MF_GRAYED);Files are attached with this post. Click to download.
No comments:
Post a Comment