通过实现ContextMenu c#winforms重命名复选框

时间:2014-12-16 05:48:14

标签: c# winforms contextmenustrip

我在面板上设置了动态创建的复选框,并且还在所有复选框上实现了ContextMenuStrip。 我无法检测到哪个控件当前显示ContextMenuStrip中定义的快捷菜单。

2 个答案:

答案 0 :(得分:1)

我得到了答案。

private void MenuViewDetails_Click(object sender, EventArgs e)    
{    
    // Try to cast the sender to a MenuItem    
    MenuItem menuItem = sender as MenuItem;    
    if (menuItem != null)    
    {    
        // Retrieve the ContextMenu that contains this MenuItem    
        ContextMenu menu = menuItem.GetContextMenu();    

        // Get the control that is displaying this context menu    
        Control sourceControl = menu.SourceControl;    
    }
}

答案 1 :(得分:0)

使用SourceControl()属性。

使用ContextMenu:

    private void menuItem1_Click(object sender, EventArgs e)
    {
        CheckBox cb = (CheckBox)contextMenu1.SourceControl;
        Console.WriteLine(cb.Name);
    }

使用ContextMenuStrip:

    private void renameToolStripMenuItem_Click(object sender, EventArgs e)
    {
        CheckBox cb = (CheckBox)contextMenuStrip1.SourceControl;
        Console.WriteLine(cb.Name);
    }