一、窗口的顶层菜单
1、创建菜单HMENU CreateMenu(VOID); //创建成功返回菜单句柄
2、增加菜单项
BOOL AppendMenu( HMENU hMenu, //菜单句柄 UINT uFlags, //菜单项风格 UINT_PTR uIDNewItem, //菜单项ID或下拉菜单的句柄 LPCTSTR lpNewItem //菜单项的名称 );
3、设置到窗口
BOOL SetMenu( HWND hWnd, //窗口句柄 HMENU hMenu //菜单句柄 );
4、三种常见风格
MF_POPUP:点击菜单弹出下拉菜单,必须填写下拉菜单的句柄
MF_STRING:被点击时发出WM_COMMAND消息,必须填写菜单项ID
MF_SEPARATOR:菜单项的分割线,一般给0
5、相关代码
case WM_CREATE:
创建顶层菜单(hWnd);
break;
void 创建顶层菜单(HWND hWnd) { //1、创建顶层菜单 HMENU hMenu= CreateMenu();//返回菜单句柄 //2、增加菜单项 AppendMenu(hMenu, MF_STRING, 1001, L"哎呦"); AppendMenu(hMenu, MF_STRING, 1001, L"不错"); //3、设置(显示)菜单 SetMenu(hWnd, hMenu); }
二、弹出式菜单
1、下拉式菜单
//1.1创建弹出菜单 HMENU hFile = CreatePopupMenu(); //在弹出菜单中添加菜单项 AppendMenu(hFile, MF_STRING, 1003, L"哎"); AppendMenu(hFile, MF_SEPARATOR, 0,L"");//分割线 AppendMenu(hFile, MF_STRING, 1004, L"呦"); AppendMenu(hMenu, MF_POPUP,(UINT)hFile,L"哎呦");
2、菜单命令处理
case WM_COMMAND: 菜单命令处理(hWnd,wParam); break; void 菜单命令处理(HWND hWnd,WPARAM wParam) { switch (LOWORD(wParam)) { case 1003: MessageBox(hWnd, L"哎哎哎哎我哎哎哎哎哎哎",L"呦",MB_OK); break; case 1004: MessageBox(hWnd, L"呦呦呦呦呦呦呦呦呦呦呦",L"哎",MB_OK); break; default: break; } }
三、菜单项状态
1、直接在前面加√
AppendMenu(hFile, MF_STRING|MF_CHECKED, 1003, L"哎");
2、菜单另起一列
AppendMenu(hFile, MF_STRING|MF_MENUBARBREAK, 1004, L"呦");
3、默认灰色,不能选择
AppendMenu(hFile1, MF_STRING|MF_GRAYED, 1005, L"不");
4、检查菜单栏
CheckMenuItem:是否被选中
EnableMenuItem:是否可用
case 1006: if (勾选状态==0) { //按菜单id值判断是否勾选 CheckMenuItem(菜单句柄, 1006, MF_BYCOMMAND | MF_UNCHECKED); } else { //按菜单索引取值 CheckMenuItem(菜单句柄, 1, MF_BYPOSITION | MF_CHECKED); } 勾选状态 = !勾选状态; break;
5、WM_INITMENUPOPUP
在菜单被激活但是未显示,窗口会收到这个消息
WPARAM:即将显示的菜单句柄
LPARAM
LOWORD:是被点击的菜单项索引
HIWORD:是窗口菜单标识 0/1
窗口菜单:顶层菜单和系统菜单属于窗口菜单,弹出式菜单不属于窗口菜单
case WM_INITMENUPOPUP: 菜单激活未显示(hWnd,wParam,lParam); break; void 菜单激活未显示(HWND hWnd,WPARAM wParam,LPARAM lParam) { wchar_t s[256] = { 0 }; swprintf_s(s,L"未显示菜单句柄:%d\n被点击菜单id:%d\n是否是窗口菜单:%d\n",wParam,LOWORD(lParam),HIWORD(lParam)); WriteConsole(输出句柄, s, wcslen(s), NULL, NULL); }