Click here to Skip to main content
Click here to Skip to main content

Dynamic Items

, 24 Feb 2003
Rate this:
Please Sign up or sign in to vote.
A class and an easy way to dynamically add items stored in a file to a menu

with System Tray

without dynamic item with dynamic items read from a file With new items read from the same modified file

with Modal Application

without dynamic item with dynamic items read from a file With new items read from the same modified file

<!------------------------------- STEP 3 ---------------------------><!-- Add the article text. Please use simple formatting (

,

etc) -->

Introduction

Creating menus can be done by building the menu statically in resources, or creating it fully dynamically using CMenu creation operation. But how dynamically add items at runtime to a menu created in resource? And how handle these items dynamically (if we don't know by advance how much they are)? Here is an easy solution.

My sample code shows you how to dynamically add and handle items to a menu in system tray, grabbing these items from an external file. The main advantage is that you can share this file on a network or else, and modify at runtime all items who are in this file.

Method

  1. First of all, create your menu in resources, including only the static items :
    Menu in resources 
    If you want no static items, but a full dynamic menu, just create a menu in the resource with dummy item like this:
    Dummy Menu in resources 
  2. Then, use the ClassWizard to create command handlers for the static items if they are some (ON_COMMAND, and ON_UPDATE_COMMAND_UI if you want to do menu enabling).

    e.g. from my sample code you have in the message map of the "MainFrame.cpp" file :

    BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
    	//{{AFX_MSG_MAP(CMainFrame)
    	ON_WM_CREATE()
    	ON_COMMAND(ID_POPUP_OPTIONS, OnPopupOptions)
    	...
    	ON_COMMAND(ID_POPUP_EXIT, OnClose)
    	//}}AFX_MSG_MAP
    END_MESSAGE_MAP()

     

  3. In the "Mainframe.h" header file, add the followings:
      #include "DynamicItems.h" to use DynamicItems class manager, and
      CDynamicItems m_DynamicItems;

    Still in "MainFrame.h", modify the message map as follow:

    	//}}AFX_MSG
    	afx_msg void OnExecuteDynamicMenu( UINT nID );
    	DECLARE_MESSAGE_MAP()

    Now, imagine you want the ability to manage a maximum of 10 dynamic items.
    (This number is a maximum, you can have less items if you want, but no more than 10 will be handled :

    In the "Mainframe.cpp" file, Add the following line in the message map:

    //}}AFX_MSG_MAP
      	ON_COMMAND_RANGE( ID_POPUP_DynCmd01, <BR>                           ID_POPUP_DynCmd01 + CDynamicMenu::GetNbMaxItems(), <BR>                           OnExecuteDynamicMenu )
    END_MESSAGE_MAP()
    

    The CDynamicMenu::GetNbMaxItems() method returns Maximum numbers of items which can be handled simultaneously on the menu.
    You can increase this static value to be sure your menu will manage a very high number of items, but don't forget you'll be limited by the size of your screen !

    This is a rarely-used but very powerful alternative message map macro, and this is the foundation of my dynamic items management.


  4. Then, in CMainframe.cpp, add for example the following code:
    void CMainFrame::OnExecuteDynamicMenu( UINT nID )
    {
            	// Retrieve the selected dynamic item Name
    
            	CString strItemText = m_DynamicItems.GetItemText(nID);
    
            	// Retrieve the selected dynamic item associated comment
            	CString strItemComment = m_DynamicItems.GetItemComment(nID);
    
            	// Display it.
    
            	CString strMsg="";
    
            	strMsg.Format("Cmd %d selected.\nItem Name: %s\nAssociated data: %s",
            		     (nID -ID_POPUP_DynCmd01), strItemText, <BR>                        strItemComment );
    
            	AfxMessageBox(strMsg);
    }
    
    This method is called every time you click on a dynamic item in the menu.
    So, you have to modify this method to handle menu as you wish.
    In the sample code, you'll see that this method contains an easy but very powerful item management... Use it and enhance it as you want !

  5. When and where do I tell my app to load my items from a file?

    Loading items from the file and updating menu in memory is done in one line of code :

      UpdateDynamicItems(strFullFilePath);
    I have decorrellated the process of physically updating data by reading a file, and the process of displaying menu for a much easier use. You can call this method when you think it is necessary : using a timer to refresh items every X minutes, or when the user right-click on an icon in the system-tray, etc... Whenever you want !
  6. Sample Code:

    There is two sample codes :

    1. A sample code which uses the system tray :
      It checks a file every X minutes using a timer to update menu (the file to check and the duration between each check is customizable). You can modify at runtime the selected file, or using the 2 files given with the sample named "TestFile.txt" and "TestFile2.txt". The header of these tests files have comments on how to format datas. When you click on an item, a message box is displayed, telling you what is the name of the selected item, and what is its associated comment.
      Usage example: An application which use a shared file containing Name/Email of present people connected to internet Wink | ;-)

    2. A modal application which allow you to load/remove menus when you want:
      This sample code shows you how to load/remove menu items on a modal application. It is very easy to implement, and very easy to use, just have a look at the code...
      Usage example: Plugin list applications which can be enhanced just by modifying the menu, or sharewares where you can add more menu items when user is regged by sending him the regged menu file, etc...

Conclusion

That's all. Your menu has now the ability to add and manage very easily dynamic items. Just have a look to the samples code to have an idea on how it works.

Use and enjoy. Please let me know of any bugs/mods/improvements that you have found/implemented and I will fix/incorporate them into this class in a future release.

Acknowledgements

Thanks to Lionel Grenier for ideas on improving this code.

Thanks Chris Maunder for his CSystemTray class used in this sample code.

History

Version 1.1 (01/27/2003):
Enhanced and easiest way to manage dynamic items.
Added new sample code with modal app.
Now the menu is really dynamic !


Version 1.0 (05/17/2001):
First "public" version.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

David Excoffier
Team Leader
France France
No Biography provided
Follow on   Twitter

Comments and Discussions

 
Generalafxwin1.inl line: 1038 debug assertion failed PinmemberRocky B.27-Aug-07 22:22 
GeneralRe: afxwin1.inl line: 1038 debug assertion failed Pinmemberkimtaehee25-Mar-08 16:45 
GeneralDynamic change of MaxItems PinmemberVjys29-Jul-07 21:25 
GeneralWindows 98: ON_UPDATE_COMMAND_UI_RANGE not called Pinmemberibthas18-Jun-07 0:02 
QuestionCan .Dat file be unicode Pinmembernix32111-Jul-06 11:01 
QuestionHow to color the menu bar PinmemberAlex Evans20-Jun-04 15:44 
GeneralMenu bar colouring PinmemberAlex Evans20-Jun-04 15:24 
How can I change the MENU BAR colour (assuming XP only) from whatever te Windows theme is
 
Hope someone can help
 
Thanks
Alex
Generald:\down\2_code\DynItems_modal_demo\DynItems_modal_demo\DynamicItems.h(146): fatal error C1083: Cannot open include file: 'fstream.h': No such file or directory Pinmemberhaoshenghan17-Jun-04 3:05 
GeneralRe: d:\down\2_code\DynItems_modal_demo\DynItems_modal_demo\DynamicItems.h(146): fatal error C1083: Cannot open include file: 'fstream.h': No such file or directory PinmemberBamaco29-Feb-05 6:06 
AnswerRe: d:\down\2_code\DynItems_modal_demo\DynItems_modal_demo\DynamicItems.h(146): fatal error C1083: Cannot open include file: 'fstream.h': No such file or directory PinmemberRenny[RuS]10-Nov-05 23:46 
GeneralRe: d:\down\2_code\DynItems_modal_demo\DynItems_modal_demo\DynamicItems.h(146): fatal error C1083: Cannot open include file: 'fstream.h': No such file or directory Pinmemberpiotrmb25-Apr-06 5:44 
GeneralRe: d:\down\2_code\DynItems_modal_demo\DynItems_modal_demo\DynamicItems.h(146): fatal error C1083: Cannot open include file: 'fstream.h': No such file or directory PinmemberRenny[RuS]26-Apr-06 0:08 
QuestionMemory leak? Pinmembersilorenz10-Mar-04 17:41 
AnswerRe: Memory leak? Pinmembersilorenz12-Mar-04 2:39 
GeneralChange the &quot;Dyn Menu&quot; entry PinmemberMichael Klim15-Jan-04 10:46 
GeneralRE: Location of TestFiles Pinmemberltayyebi27-Aug-03 6:55 
GeneralRe: RE: Location of TestFiles PinmemberDavid Excoffier27-Aug-03 8:51 
GeneralMDI Bug/Assert Fix PinmemberSully27-Feb-03 12:10 
QuestionHot Coffee? PinmemberJörgen Sigvardsson24-Feb-03 22:36 
AnswerRe: Hot Coffee? PinmemberAndreas Saurwein25-Feb-03 0:12 
GeneralGreat Job & little improvement Pinmemberlebios31-Dec-02 10:54 
GeneralRe: Great Job & little improvement PinmemberEPHERE6-Feb-03 12:45 
GeneralRe: Great Job & little improvement PinmemberDavid Excoffier7-Feb-03 1:57 
GeneralPerformed an illegal operation... PinmemberKing Coffee4-Nov-02 13:26 
GeneralCool mais PinmemberMoz29-May-01 23:07 
GeneralRe: Cool mais PinmemberLaurent Kempé30-May-01 12:41 
GeneralRe: Cool mais PinmemberTomas Petricek20-Sep-02 11:06 
GeneralRe: Cool mais PinmemberDavid Excoffier19-Oct-02 7:22 
GeneralRe: Cool mais PinmemberM A V30-Apr-03 13:20 
GeneralRe: Cool mais Pinmemberlallous10-Dec-06 23:01 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.141220.1 | Last Updated 25 Feb 2003
Article Copyright 2001 by David Excoffier
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid