Click here to Skip to main content
15,868,016 members
Articles / Desktop Programming / MFC
Tip/Trick

Adding Dynamic Sub menu to the Menu, Add Event Handler for Each Individual Sub menu

Rate me:
Please Sign up or sign in to vote.
4.33/5 (2 votes)
4 Aug 2013CPOL1 min read 17.5K   4   6   2
How to add sub menus dynamically, adding event for them and also retrieving the menu name on click event of individual sub menu
Image 1

Introduction

This post discusses how to add sub menu dynamically to the main menu so pop up menu goes on increasing as user does some action on the main menu like hide in my case.

Background

In one of the applications, there was a requirement of adding dynamic pop up menu to the bar, when user would click on hide menu. As the user goes on clicking on hide bars, the individual bars name should keep on getting added to the sub menu. Please refer to the snapshot above for more details.

Using the Code

The below code is useful to add sub menu to the menu dynamically on right click on each selected bar:

C++
 void CMyListDlg::OnRclickList(NMHDR* pNMHDR, LRESULT* pResult)
 {
    // TODO: Add your control notification handler code here
   int nIndex = m_List.GetSelectionMark();
   CString pString = m_List.GetItemText(nIndex,1);
   CMenu menu, * pSubMenu; 
   int pos=0; menu.LoadMenu(IDR_MENU1); 
   menu.GetSubMenu(0)->GetSubMenu(0)->InsertMenu(pos,MF_BYPOSITION,ID_COMMAND_START,pString)) 
}

Once the sub menu has been added to the main menu, we need to show the bar once user has clicked on each sub menu in the list.

In my case, almost 20 sub menus have been added to the list. So we have to use ON_COMMAND_RANGE to assign ID to each sub menu added to the list. It will help us to add our show bar code on clicking of individual hidden bar.

C++
ON_COMMAND_RANGE(ID_COMMAND_START,  ID_COMMAND_END, OnClickAdd)
 
 --------
 
--- OnClickAdd(UINT id)
{
   CString str;
   MSG pMsg = AfxGetThreadState()->m_lastSentMsg;
   pMsg.wParam &= 0xFFFF;
   menu.GetMenuString(LOWORD(pMsg.wParam) , str,true);
     or
  menu.GetMenuString(id , str,true);
} 

The "str" will give you the sub menu name as per your selected sub menu in the list.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
Working as a software profesional in Pvt firm
More than 7+ yrs of exp in the field of C++,VC++,MFC,COM,SQL server etc

Comments and Discussions

 
Newsmissing attachments Pin
Joezer BH4-Aug-13 20:23
professionalJoezer BH4-Aug-13 20:23 
GeneralRe: missing attachments Pin
skyformat99@gmail.com5-Aug-13 0:04
skyformat99@gmail.com5-Aug-13 0:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.