我有一个 win32 应用程序 (c++),它有一个上下文菜单绑定(bind)到右键单击通知图标。菜单/子菜单项在运行时动态创建和更改。
InsertMenu(hSettings, 0, MF_BYPOSITION | MF_POPUP | MF_STRING, (UINT_PTR) hDevices, L"Setting 1");
InsertMenu(hSettings, 1, MF_BYPOSITION | MF_POPUP | MF_STRING, (UINT_PTR) hChannels, L"Setting 2");
InsertMenu(hMainMenu, 0, MF_BYPOSITION | MF_POPUP | MF_STRING, (UINT_PTR) hSettings, L"Settings");
InsertMenu(hMainMenu, 1, MF_BYPOSITION | MF_STRING, IDM_EXIT, L"Exit");
在上面的代码中,hDevices 和 hChannels 是动态生成的子菜单。 动态菜单是这样生成的:
InsertMenu(hDevices, i, style, IDM_DEVICE, L"Test 1");
InsertMenu(hDevices, i, style, IDM_DEVICE, L"Test 2");
InsertMenu(hDevices, i, style, IDM_DEVICE, L"Test 3");
有没有办法知道点击了哪个项目,而不必为每个子菜单项定义它自己的 ID(上面代码中的 IDM_DEVICE)? In 想要检测用户单击了子菜单 IDM_DEVICE 并且他单击了该子菜单中的第一项(测试 1)。
我想实现这样的目标:
case WM_COMMAND:
wmId = LOWORD(wParam);
wmEvent = HIWORD(wParam);
// Parse the menu selections:
switch (wmId)
{
case IDM_DEVICE: // user clicked on Test 1 or Test 2 or Test 3
UINT index = getClickedMenuItem(); // get the index number of the clicked item (if you clicked on Test 1 it would be 0,..)
// change the style of the menu item with that index
break;
}
最佳答案
尝试以下操作:
MENUINFO mi;
memset(&mi, 0, sizeof(mi));
mi.cbSize = sizeof(mi);
mi.fMask = MIM_STYLE;
mi.dwStyle = MNS_NOTIFYBYPOS;
SetMenuInfo(hDevices, &mi);
现在您将获得 WM_MENUCOMMAND
而不是 WM_COMMAND
。菜单索引将在 wParam 中,而菜单句柄将在 lParam 中。注意只吃掉已知菜单的消息,并将其余的传递给 DefWindowProc
。代码将与此类似:
case WM_MENUCOMMAND:
HMENU menu = (HMENU)lParam;
int idx = wParam;
if (menu == hDevices)
{
//Do useful things with device #idx
}
else
break; //Ensure that after that there is a DefWindowProc call
关于c++ win32动态菜单 - 选择了哪个菜单项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7541750/