Click here to Skip to main content
15,867,704 members
Articles / Desktop Programming / MFC

Dynamic Items

Rate me:
Please Sign up or sign in to vote.
4.93/5 (15 votes)
24 Feb 20034 min read 200.2K   6.7K   85   30
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

Introduction

Creating menus can be done by building the menu statically in resources, or creating it fully dynamically using CMenu creation operation. But how to dynamically add items at runtime to a menu created in resource? And how to 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 that 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 there 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:

    C++
    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 following:
    #include "DynamicItems.h" to use DynamicItems class manager, and:
    C++
    CDynamicItems m_DynamicItems;
    

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

    C++
    //}}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:

    C++
    //}}AFX_MSG_MAP
      	ON_COMMAND_RANGE( ID_POPUP_DynCmd01, 
                               ID_POPUP_DynCmd01 + CDynamicMenu::GetNbMaxItems(), 
                               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:
    C++
    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, 
                            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:

    C++
    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-clicks on an icon in the system-tray, etc... Whenever you want!
  6. Sample Code:

    There are 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 uses a shared file containing Name/Email of present people connected to the internet ;-)
    2. A modal application which allows 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 now has the ability to add and manage dynamic items very easily. Just have a look at the samples code to have an idea of 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.


Written By
Team Leader
France France
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Generalafxwin1.inl line: 1038 debug assertion failed Pin
Rocky B.27-Aug-07 21:22
Rocky B.27-Aug-07 21:22 
GeneralRe: afxwin1.inl line: 1038 debug assertion failed Pin
kimtaehee25-Mar-08 15:45
kimtaehee25-Mar-08 15:45 

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.