Create a Dynamic Menu Using C#

There have been articles on the technique of creating MRU (Most Recently Used) file menus in Visual Studio environment.

In my recent project, I need not only to create a MRU file menu, but also other menus that are dynamically created. For example, a user-customizable tools menu, help menu, and so forth. This article generalizes the way of creating a MRU menu to introduce the concept of a Dynamic Menu, which is created dynamically at application execution time.

One thing in common in the menus my application needs to create is that each dynamic menu item is associated with data. In the case of a MRU file menu item, it is the file path to be opened, and in the case of a tools menu item, it is the path of an application to be invoked. When it comes to a user-customizable help menu, it is a document file of various types to be displayed.

In all these cases, the data associated with a menu item is of string type. It does not prevent you to make it an object to be more general. The MenuItem class in System.Windows.Forms namespace has the object type property Tag that can be used to store user data. You can utilize this placeholder to store the data of dynamic menu items, but I prefer to derive a class from the MenuItem item class.

This allows you to further expand this class in the future when needed, and also it makes the code easy to understand. In my example code, the derived class is named DynamicMenuItem. To simplify the code, I make this data member string type, which meets the needs of MRU file menu and tools menu.

To add dynamic menu items to a menu list, a dynamic menu manager class is designed. The manager class controls the type of dynamic menu list and the way to add a menu item to the menu list that I will explain in detail.

Continue reading at CodeGuru.