Making a Context Menu

Shows you how to make a context menu (right click / shortcut menu) in C# using Visual C# .NET and how to attach it to a control.

You can hardly find an application that doesn’t use any context menu. Adding a context menu to your application isn’t hard at all, thanks to Visual C# .NET.

Start a new Windows Application project. Look in the Toolbox for ContextMenu:

Add it to the form by double clicking or dragging. After the context menu is added to the application project, when you click on it at the top of the form, below the Title Bar the menu appears waiting to be edited. Of course, that’s not where the menu appears when you run the application. The menu appears when you right click the control.

Let’s add a few items to the menu. You can add new items just by clicking on the Type Here area. In the following screenshot you can see we added 3 items (Help -> About and Exit):

You can add code to the click event of an item the same way you would with any control. Select the item and switch to Events in the properties window and double click the Click event. This will take you to where you need to insert the code for the event. Here is the code for the event of the ‘Exit’ item:

private void menuItem3_Click(object sender, System.EventArgs e)

{

   Application.Exit();

}

Ok, we have created the context menu now we need to attach it to the control we need to have a context menu when it is right clicked.

You can attach a context menu to any control that has a ContextMenu property. To a Form, to a ListView, to a DataGrid, just use the Properties window to select a context menu:

And here’s the result to attaching the context menu to a form:

Nathan Pakovskie is an esteemed senior developer and educator in the tech community, best known for his contributions to Geekpedia.com. With a passion for coding and a knack for simplifying complex tech concepts, Nathan has authored several popular tutorials on C# programming, ranging from basic operations to advanced coding techniques. His articles, often characterized by clarity and precision, serve as invaluable resources for both novice and experienced programmers. Beyond his technical expertise, Nathan is an advocate for continuous learning and enjoys exploring emerging technologies in AI and software development. When he’s not coding or writing, Nathan engages in mentoring upcoming developers, emphasizing the importance of both technical skills and creative problem-solving in the ever-evolving world of technology. Specialties: C# Programming, Technical Writing, Software Development, AI Technologies, Educational Outreach

Leave a Reply

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

Back To Top