MSDN Documentation

Microsoft Developer Network

Menus in the Windows API

Menus are a fundamental part of the graphical user interface (GUI) in Windows applications. They provide a structured way for users to select commands and options within an application. The Windows API offers a comprehensive set of functions and structures for creating, managing, and displaying menus.

Overview of Menu Concepts

A menu is typically composed of:

Key Structures and Functions

Structures

Core Functions

Creating a Simple Menu

The process of creating a menu typically involves:

  1. Creating the main menu handle using CreateMenu.
  2. Creating pop-up menus for top-level items using CreatePopupMenu.
  3. Adding menu items to the pop-up menus using AppendMenu or InsertMenuItem.
  4. Associating the pop-up menus with the main menu using AppendMenu.
  5. Assigning the main menu to the window using SetMenu.

Example: Adding a "File" Menu

Here's a conceptual C++ snippet showing how to add a simple "File" menu:


// Assume hwnd is the handle to your window
HMENU hMenu = CreateMenu();
HMENU hFileMenu = CreatePopupMenu();

// Add items to the File menu
AppendMenu(hFileMenu, MF_STRING, IDM_FILE_NEW, TEXT("New"));
AppendMenu(hFileMenu, MF_STRING, IDM_FILE_OPEN, TEXT("Open"));
AppendMenu(hFileMenu, MF_SEPARATOR, 0, NULL); // Add a separator
AppendMenu(hFileMenu, MF_STRING, IDM_FILE_EXIT, TEXT("Exit"));

// Add the File menu to the main menu bar
AppendMenu(hMenu, MF_POPUP | MF_STRING, (UINT_PTR)hFileMenu, TEXT("File"));

// Set the menu for the window
SetMenu(hwnd, hMenu);
            

Handling Menu Commands

When a user selects a menu item, the system sends a WM_COMMAND message to the window procedure of the window that owns the menu. The wParam of this message contains the identifier of the selected menu item.


LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
    switch (uMsg) {
        case WM_COMMAND: {
            int wmId = LOWORD(wParam);
            // Parse the menu selections:
            switch (wmId) {
                case IDM_FILE_NEW:
                    // Handle "New" command
                    MessageBox(hwnd, TEXT("New command selected!"), TEXT("Info"), MB_OK);
                    break;
                case IDM_FILE_EXIT:
                    PostQuitMessage(0);
                    break;
                default:
                    return DefWindowProc(hwnd, uMsg, wParam, lParam);
            }
            break;
        }
        // ... other messages
        default:
            return DefWindowProc(hwnd, uMsg, wParam, lParam);
    }
    return 0;
}
            

Advanced Menu Features

Note: Always remember to destroy menus using DestroyMenu when they are no longer needed to prevent memory leaks.
Tip: Consider using resource files (.rc) for defining your application's menus. This separates UI elements from code and simplifies management.