Search code examples
menumacos-carbon

MenuRef GetControl32BitValue always return 0


Hello i' need to use a pop-up menu, witch is created dynamically.


OSErr err = GetBevelButtonMenuHandle(m_pRecallAOptionalButton, &m_pRecallAMenuRef);

for (countitem)
{
 String szItem (List.GetAt(i));
 CFStringRef sz = ToCFStringRef(szItem);
 AppendMenuItemTextWithCFString(m_pRecallAMenuRef, sz, 0, 0, 0);
}

short  sCount = CountMenuItems(m_pRecallAMenuRef);
SetControl32BitMaximum(m_pRecallAOptionalButton, sCount);

This is ok, menu show the correct number of items. I set maximum value.

My problem occur when i want to get the selected item index. For this, i use the kEventClassMenu event & kEventMenuClosed kind


case kEventClassMenu:
{
    MenuRef Menu;
    GetEventParameter( inEvent, kEventParamDirectObject, typeMenuRef, NULL, sizeof(Menu), NULL, &Menu );

    if (Menu && (Menu == pMainForm->m_pRecallAMenuRef))
    {
      SInt32 nIndex = GetControl32BitMaximum(m_pRecallAOptionalButton); // return the correct items count
      nIndex = GetControl32BitValue(m_pRecallAOptionalButton); // always return 0 !!!!!
    }
}

Did i missed something ? is it the right event to attach ?

Many thanks for help.


Solution

  • You probably want to handle kEventClassCommand/kEventProcessCommand, and use the command id from the menu item.

    HICommand           command;
    
    GetEventParameter( inEvent, kEventParamDirectObject, typeHICommand, NULL,
                sizeof( HICommand ), NULL, &command );
    
    switch (command.commandID) {
        case 1:
          ... etc ...
    

    Note that the commandID is one of the parameters to AppendMenuItemTextWithCFString; that's how you can give each item a unique commandID as you generate the menu. commandID's are conventionally 4-char codes (like 'open' or 'save'), but there's no reason you couldn't use simple ints for your dynamically-generated commands.