C#: dynamically add a context Menu in run time

The following code can add a context menu as well as the code that gets executed when you click on Context Menu Item in run time.Normally, you design the context menu by using the Visual Studio IDE. However, you can dynamically create a new context menu as well as context menu items and the event handler, so it gets executed in the run time.

 


private void AddContextMenu()
        {
            System.Windows.Forms.ContextMenuStrip contextMenuStrip_Registry = new System.Windows.Forms.ContextMenuStrip();
            System.Windows.Forms.ToolStripMenuItem copyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            contextMenuStrip_Registry.SuspendLayout();
 
            // contextMenuStrip_Registry
            // 
            contextMenuStrip_Registry.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            copyToolStripMenuItem});
            contextMenuStrip_Registry.Name = "contextMenuStrip_Registry";
            contextMenuStrip_Registry.Size = new System.Drawing.Size(153, 48);
            // 
            // copyToolStripMenuItem
            // 
            copyToolStripMenuItem.Name = "copyToolStripMenuItem";
            copyToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
            copyToolStripMenuItem.Text = "C&opy";
            copyToolStripMenuItem.Click += (sender, e) //copy the registry key value with new context menu item copy
                => {
                        if (myLSV.SelectedItems.Count > 0)
                        {
                            string tag = myLSV.SelectedItems[0].Tag.ToString();
                            System.Windows.Forms.Clipboard.SetText(tag);
                        }           
            };
 
 
            contextMenuStrip_Registry.ResumeLayout(false);
 
            myLSV.ContextMenuStrip = contextMenuStrip_Registry;
 
        }

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>