2011-09-24 20 views
5

tengo una aplicación win32 (C++) que tiene un menú contextual que se une al clic derecho en el ícono de notificación. Los elementos del menú/submenú se crean y cambian dinámicamente durante el tiempo de ejecución.menú dinámico C++ win32 - qué elemento del menú se seleccionó

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"); 

En el código anterior, hDevices y hChannels son submenús generados dinámicamente. Los menús dinámicos se generan de esta manera:

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"); 

¿Hay alguna manera de saber qué elemento se ha hecho clic sin tener que definir cada elemento de submenú su propio ID (IDM_DEVICE en el código anterior)? En desea detectar que el usuario hizo clic en el submenú IDM_DEVICE y que hizo clic en el primer elemento (Prueba 1) en este submenú.

me gustaría achive algo como esto:

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

Respuesta

6

intente lo siguiente:

MENUINFO mi; 
memset(&mi, 0, sizeof(mi)); 
mi.cbSize = sizeof(mi); 
mi.fMask = MIM_STYLE; 
mi.dwStyle = MNS_NOTIFYBYPOS; 
SetMenuInfo(hDevices, &mi); 

Ahora obtendrá el WM_MENUCOMMAND en lugar de WM_COMMAND. El índice del menú estará en wParam y el control del menú en lParam. Tenga cuidado de consumir mensajes solo para menús conocidos y pasar el resto al DefWindowProc. El código será similar a esto:

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

gracias ¡he estado buscando todo el día por una muestra y no he podido encontrar ninguna! – blejzz

0

También se puede utilizar TrackPopupMenuEx() con las banderas TPM_RETURNCMD | TPM_NONOTIFY y obtener el id del elemento de menú seleccionado sin tener que ir a través WM_MENUCOMMAND.

Cuestiones relacionadas