HomeC&C++WainTutorialsSamplesTip&TrickTools


Next step is to add a menu to the application.
We could do it from a resource file (a .rc file) but I will do it in the code.
First we must define som identifiers for our menu items:
enum MenuCommand
{
   FileOpenCmd = 1000,
   FileSaveCmd,
   FileCloseCmd,
   AboutCmd
};
This will create some ids with number 1000, 1001, etc. We could use almost any number less than 0x10000, but the first numbers are normally used for identifiers for windows and dialogs.
First we create the File menu:
   HMENU FileMenu = CreateMenu();
   AppendMenu(FileMenu, MF_STRING, FileOpenCmd, "Open");
   AppendMenu(FileMenu, MF_STRING, FileSaveCmd, "Save");
   AppendMenu(FileMenu, MF_SEPARATOR, 0 , 0);
   AppendMenu(FileMenu, MF_STRING, FileCloseCmd, "Close");
Then a Help menu, with only one item:
   HMENU HelpMenu = CreateMenu();
   AppendMenu(HelpMenu, MF_STRING, AboutCmd, "About");
Then we create the main menu, and insert the two menus from above into this menu:
   HMENU MainMenu = CreateMenu();
   AppendMenu(MainMenu, MF_POPUP, (UINT )FileMenu, "File");
   AppendMenu(MainMenu, MF_POPUP, (UINT )HelpMenu, "Help");
We can now use this MainMenu when we create the Window:
    return CreateWindow("SimpleWinWndClass",
                       "Simple-Window",
                       WS_MINIMIZEBOX | WS_VISIBLE |
                       WS_CLIPSIBLINGS | WS_CLIPCHILDREN |
                       WS_MAXIMIZEBOX | WS_CAPTION |
                       WS_BORDER | WS_SYSMENU | WS_THICKFRAME,
                       CW_USEDEFAULT, 0, CW_USEDEFAULT, 0,
                       0,
                       MainMenu,
                       InstanceHandle,
                       0);
Then menu should now be visible when you run the applikation.
We just need to ad some handling of the messages received when the user select the menu items.
This could be done with this code, added to the switch in MainWndProc:
     case WM_COMMAND:
      switch(LOWORD(wParam))
      {
      case FileOpenCmd:
         MessageBox(hwnd, "Open", "Test", MB_OK);
         break;
      case FileSaveCmd:
         MessageBox(hwnd, "Save", "Test", MB_OK);
         break;
      case FileCloseCmd:
         MessageBox(hwnd, "Close", "Test", MB_OK);
         break;
      case AboutCmd:
         MessageBox(hwnd, "About", "Test", MB_OK);
         break;
      }
      break;

The complete code for the application can be found here