Menu.GetContextMenu 方法

定义

获取包含该菜单的 ContextMenu

C#
public System.Windows.Forms.ContextMenu GetContextMenu();

返回

包含该菜单的 ContextMenu。 默认值为 null

示例

在此示例中,使用 GetContextMenu 方法获取对包含 或 menuItem2的快捷菜单的menuItem1引用,并在消息框中显示快捷菜单信息。 以编程方式创建包含两个项 NewOpen的快捷菜单。 然后,通过创建适当的事件处理程序向这些项添加功能。 运行该示例时,你会收到一个消息框,指示右键单击窗体以显示快捷菜单。 然后,单击菜单项时,会收到另一条消息,告知已单击哪个项,并在包含的快捷菜单上显示信息。 此示例要求已创建名为 FormForm1

C#
public void AddContextmenu()
{
    // Create a shortcut menu.
    ContextMenu m = new ContextMenu();
    this.ContextMenu= m;

    // Create MenuItem objects.
    MenuItem menuItem1 = new MenuItem();
    MenuItem menuItem2 = new MenuItem();
    
    // Set the Text property.
    menuItem1.Text = "New";
    menuItem2.Text = "Open";

    // Add menu items to the MenuItems collection.
    m.MenuItems.Add(menuItem1);
    m.MenuItems.Add(menuItem2);

    // Display the starting message.
    MessageBox.Show("Right-click the form to display the shortcut menu items");

    // Add functionality to the menu items. 
    menuItem1.Click += new System.EventHandler(this.menuItem1_Click);
    menuItem2.Click += new System.EventHandler(this.menuItem2_Click);
    }

private void menuItem1_Click(object sender, System.EventArgs e)
{
    string textReport =	"You clicked the New menu item. \n" +
        "It is contained in the following shortcut menu: \n\n"; 

    // Get information on the shortcut menu in which menuitem1 is contained.
    textReport += ContextMenu.GetContextMenu().ToString();

    // Display the shortcut menu information in a message box.
    MessageBox.Show(textReport,"The ContextMenu Information");		
}

private void menuItem2_Click(object sender, System.EventArgs e)
{
    string textReport =	"You clicked the Open menu item. \n" +
        "It is contained in the following shortcut menu: \n\n"; 

    // Get information on the shortcut menu in which menuitem1 is contained.
    textReport += ContextMenu.GetContextMenu().ToString();

    // Display the shortcut menu information in a message box.
    MessageBox.Show(textReport,"The ContextMenu Information");		
}

注解

此方法允许您获取对包含此菜单的 的引用 ContextMenu 。 如果菜单不包含在 中,ContextMenu则此属性返回 null 。 如果菜单包含在 或 MainMenu中,MenuItem或者菜单未包含在任何菜单中,则可能会发生这种情况。 可以使用此属性来确定当前是否正在使用菜单,还可以确定在何处使用。

适用于

产品 版本
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 10

另请参阅