2011-09-24 120 views
5

我有一个win32应用程序(C++),它有一个上下文菜单绑定到通知图标上的右键单击。菜单/子菜单项是在运行时动态创建和更改的。C++ win32动态菜单 - 哪个菜单项被选中

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在上面的代码中),其项知道的方法吗?在想要检测到用户点击了子菜单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;   
    } 

回答

6

尝试以下操作:

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 
+0

谢谢我一直在搜索一个样本,找不到任何! – blejzz

0

你也可以使用TrackPopupMenuEx()与标志TPM_RETURNCMD | TPM_NONOTIFY并获得选择的菜单项的id,而不必去通WM_MENUCOMMAND