When developing applications, we often need to use the pop-up menu. Sometimes, you need to implement this function when you click a control.
. NET provides a ContextMenuStrip control that can be bound to other controls. When you click this control, the corresponding menu is displayed.
However, there is a problem in doing so. The trigger condition of ContextMenuStrip is that the control to which it is bound is right-clicked.
If all interface operations of an application are completed by clicking or double-clicking, you must right-click a widget. This situation is a bit unpleasant.
Is there any way to trigger the pop-up menu by clicking the left button? Of course, the answer is yes. This method is described as follows:
- First, create a ContextMenuStrip, get the name, and set the relevant attributes. Here we name the control ctxMenu
- Next, create a control to trigger the menu, which can be any control. Here we use a Button control named btnMenu.
- Then there is the code part. A very simple code:
Private void btnMenu_Click (object sender, EventArgs e)
{
// Parameter 1 is the bound control
// Parameter 2 indicates the position where the pop-up menu is displayed (0, 0 matches the origin of the bound control)
CtxMenu. Show (btnMenu, new Point (0, btnMenu. Height + 5 ));
}
Note: of course, this code is not perfect, because the menu is displayed either by clicking the left button or by right-clicking. You can write the code to the mouse event of the control, click the left and right buttons to solve the problem.