c ++ win32动态菜单 - 选择了哪个菜单项

时间:2011-09-24 20:33:37

标签: c++ winapi menu selected submenu

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

 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;          
    }

2 个答案:

答案 0 :(得分:7)

尝试以下方法:

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

答案 1 :(得分:0)

还可以将export class GlobalValidation { static emailPattern(control: AbstractControl): ValidationResult { var EMAIL_REGEXP = Pattern.EMAIL; if (control.value != "" && !URL_REGEXP.test(control.value)) { return {"incorrectPatternFormat": true}; } return null; } static urlPattern(control: AbstractControl): ValidationResult { var URL_REGEXP = Pattern.URL; if (control.value != "" && !URL_REGEXP.test(control.value)) { return {"incorrectPatternFormat": true}; } return null; } } 与标记TrackPopupMenuEx()一起使用,并获取所选菜单项的TPM_RETURNCMD | TPM_NONOTIFY,而无需通过id