Usage of ContextMenuStrip (right mouse click menu) in C# Windows form design

Abstract: ContextMenuStrip, an advanced development of Winform, uses its own development experience to explain the specific usage of ContextMenuStrip.

Programming language: C#

Programming environment: Visual Studio 2019

Problem Description

        Is there anyone who wants to add a right-click menu to the control, but clicks on the property box and finds...

        Oh my God, this is actually none, so how do you add a right-click menu? The editor fumbled and summed up two adding methods.

Method 1: Add through the toolbox ContextMenuStrip control

        First of all, the editor struggled with why it was none, thinking whether there is currently no such control to choose from, so I went to the toolbox to look for it. Sure enough, guess what.

        It should be it, I can't wait to drag one out, edit it.

 

        Then, at this time, I will click on the place that originally displayed nothing.

 

        Nice! Click to add contextMenuStrip1, run it to see if it works. 

        success! In this way, you can add the right-click menu to the control you want to add at will.

Method 2: Add by writing code

        In fact, when I used it for the first time, I wrote code to import it myself. At that time, I thought that all controls could be added by writing code, and ContextMenuStrip was no exception. Still in this project, add a button button1, add a right-click menu to it by writing code, and write the following code into the constructor of Form1.

public Form1()
        {
            InitializeComponent();

            ContextMenuStrip contextMenuStrip = new ContextMenuStrip();//创建一个鼠标右击菜单

            /*添加项*/
            contextMenuStrip.Items.Add("我");
            contextMenuStrip.Items.Add("很");
            contextMenuStrip.Items.Add("强");

            button1.ContextMenuStrip = contextMenuStrip;//右击菜单添加到按钮button1
        }

        Run it to see the effect.

        Also perfect hehe.

summary 

        This article talks about how to create and add the ContextMenuStrip of the mouse right-click menu. As for the functions required by the click item, it is the same as the normal button control, register the mouse click event, and write the function to the event method body.

each message

        The most difficult time is when we are not far from success.

Guess you like

Origin blog.csdn.net/lucgh/article/details/130090574
Recommended