Pages

Sunday, August 1, 2010

Win32: Create window menu programmatically

Standard Windows application contains a menu. Usualy we create the menu in the application resource file. Then load it and pass the menu handle whithin the window class regisration procvedure.
How to create the standard windows menu programmatically?
CreateMenu function in the following Win32 program does it:
#define WIN32_LEAN_AND_MEAN

#include <windows.h>

LPCWSTR s_szWndName = L"A window with a menu";

ATOM RegisterWndClass(HINSTANCE, LPCWSTR);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);

void CreateAMenu(HWND hWnd);

int WINAPI wWinMain(HINSTANCE hInstance,
HINSTANCE, LPWSTR, int nShowCmd)
{
RegisterWndClass(hInstance, s_szWndName);

HWND hWnd = CreateWindow(s_szWndName, s_szWndName,
WS_OVERLAPPEDWINDOW | WS_CLIPSIBLINGS | WS_CLIPCHILDREN,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0,
NULL, NULL, hInstance, NULL);

if (hWnd != NULL)
{
ShowWindow(hWnd, nShowCmd);
UpdateWindow(hWnd);

MSG msg = { 0 };
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}

return 0;
}

ATOM RegisterWndClass(HINSTANCE hInstance,
LPCWSTR lpszWndClassName)
{
WNDCLASSEX wcex = { 0 };
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.hInstance = hInstance;
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wcex.lpszMenuName = NULL;
wcex.lpszClassName = lpszWndClassName;
return RegisterClassEx(&wcex);
}

LRESULT CALLBACK WndProc(HWND hWnd, UINT message,
WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_CREATE:
CreateAMenu(hWnd);
break;

case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
EndPaint(hWnd, &ps);
}
break;

case WM_LBUTTONDOWN:
PostMessage(hWnd, WM_CLOSE, 0, 0);
break;

case WM_DESTROY:
PostQuitMessage(0);
break;

    default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}

#define ID_NEW_RECORD_ITEM 1001
#define ID_SAVE_RECORD_ITEM 1002
#define ID_QUIT_ITEM 1003
#define ID_SHOW_ALL_ITEM 1004
#define ID_SELECT_REPORT_ITEM 1005


void CreateAMenu(HWND hWnd)
{
HMENU hMenu = CreateMenu();
HMENU hSubMenu = CreatePopupMenu();

AppendMenu(hSubMenu, MF_STRING, ID_NEW_RECORD_ITEM, L"&New Record");
AppendMenu(hSubMenu, MF_STRING, ID_SAVE_RECORD_ITEM, L"&Save Record");
AppendMenu(hSubMenu, MF_STRING, ID_QUIT_ITEM, L"&Quit");
AppendMenu(hMenu, MF_STRING | MF_POPUP, (UINT)hSubMenu, L"&File");

hSubMenu = CreatePopupMenu();
AppendMenu(hSubMenu, MF_STRING, ID_SHOW_ALL_ITEM, L"Show &All Data");
AppendMenu(hSubMenu, MF_STRING, ID_SELECT_REPORT_ITEM, L"S&eelect report");
AppendMenu(hMenu, MF_STRING | MF_POPUP, (UINT)hSubMenu, L"&Reports");

SetMenu(hWnd, hMenu);
}

2 comments: