一、菜单资源的使用
1.菜单的分类
- 窗口的顶层菜单
- 弹出式菜单
- 系统菜单
HMENU类型表示菜单,ID表示菜单项
2、菜单资源的使用
(1).注册窗口类时设置菜单
(2).创建窗口传参设置菜单
(3).在主窗口WM_CREATE消息中利用SetMenu函数设置菜单
加载菜单资源
HMENU LoadMenu( HINSTANCE hInstance, LPCTSTR lpMenuName );
示例代码:
#include <Windows.h> #include <stdio.h> #include "resource.h" HINSTANCE g_hIns = NULL; //窗口处理函数(自定义,处理消息) LRESULT CALLBACK WindProc(HWND hWnd, UINT msgID, WPARAM wParam, LPARAM lParam) { switch (msgID) { case WM_CREATE: { HMENU hMenu = LoadMenu(g_hIns, (LPCWSTR)IDR_MENU1); SetMenu(hWnd, hMenu); break; } default: break; } return DefWindowProc(hWnd, msgID, wParam, lParam); } //入口函数 int CALLBACK WinMain(HINSTANCE hIns, HINSTANCE hPreIns, LPSTR lpCmdLine, int nCmdShow) { g_hIns = hIns; //设计窗口类 WNDCLASS wc = { 0 }; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); wc.hCursor = NULL; wc.hIcon = NULL; wc.hInstance = hIns; wc.lpfnWndProc = WindProc; wc.lpszClassName = TEXT("Main"); //1.注册窗口类时设置菜单 //wc.lpszMenuName = (LPCWSTR)IDR_MENU1; wc.lpszMenuName = NULL; wc.style = CS_HREDRAW | CS_VREDRAW | CS_DBLCLKS; //2.创建窗口传参设置菜单 //HMENU hMenu = LoadMenu(hIns, (LPCWSTR)IDR_MENU1); //注册窗口类 RegisterClass(&wc);//将以上所有赋值全部写入操作系统 //在内存中创建窗口 //HWND hWnd = CreateWindowEx(0, wc.lpszClassName, TEXT("Window"), WS_OVERLAPPEDWINDOW, 100, 100, 500, 500, NULL, hMenu, hIns, NULL); HWND hWnd = CreateWindowEx(0, wc.lpszClassName, TEXT("Window"), WS_OVERLAPPEDWINDOW, 100, 100, 500, 500, NULL, NULL, hIns, NULL); //显示窗口 ShowWindow(hWnd, SW_SHOW); UpdateWindow(hWnd); //消息循环 MSG nMsg = { 0 }; while (true) { if ((PeekMessage(&nMsg, NULL, 0, 0, PM_NOREMOVE))) { //有消息 if (GetMessage(&nMsg, NULL, 0, 0)) { TranslateMessage(&nMsg); DispatchMessage(&nMsg); } else { break; } } } return 0; }
3、菜单命令消息处理
菜单消息:WM_COMMAND
附带参数信息:
wPARAM:HIWORD:对于菜单为0,LOWORD:菜单项的ID
lPARAM:对于菜单为0
示例代码:
void onCommand(HWND hWnd, WPARAM wParam) { switch (LOWORD(wParam)) { case ID_NEW: MessageBox(hWnd, TEXT("新建被点击"), TEXT("提示"), MB_OK); break; case ID_EXIT: MessageBox(hWnd, TEXT("退出被点击"), TEXT("提示"), MB_OK); break; case ID_ABOUT: MessageBox(hWnd, TEXT("关于被点击"), TEXT("提示"), MB_OK); break; default: break; } } //窗口处理函数(自定义,处理消息) LRESULT CALLBACK WindProc(HWND hWnd, UINT msgID, WPARAM wParam, LPARAM lParam) { switch (msgID) { case WM_CREATE: { HMENU hMenu = LoadMenu(g_hIns, (LPCWSTR)IDR_MENU1); SetMenu(hWnd, hMenu); break; } case WM_COMMAND: { onCommand(hWnd, wParam); break; } default: break; } return DefWindowProc(hWnd, msgID, wParam, lParam); }
标签:hIns,文件,菜单,wc,hWnd,编程,Win32,break,NULL From: https://www.cnblogs.com/TechNomad/p/17692270.html