多个控件的 Windows 窗体右键菜单

che*_*525 3 c# winforms

我的 Windows 窗体中有多个控件,我希望右键单击每个控件时都弹出相同的菜单。但是,根据单击的控件的不同,操作应略有不同。

我遇到的问题是 ToolStripMenuItem 没有任何有关最初单击哪个控件以使工具条可见的信息。我真的不想每个控件都需要一个单独的上下文菜单!

到目前为止,我的代码看起来像这样:

private void InitializeComponent()
{
    this.openMenuItem = new ToolStripMenuItem();
    this.openMenuItem.Text = "Open";
    this.openMenuItem.Click += new EventHandler(this.openMenuItemClick);

    this.runMenuItem = new ToolStripMenuItem();
    this.runMenuItem.Text = "Run";
    this.runMenuItem.Click += new EventHandler(this.runMenuItemClick);

    this.contextMenuStrip = new ContextMenuStrip(this.components);
    this.contextMenuStrip.Items.AddRange(new ToolStripMenuItem[]{
        this.openMenuItem,
        this.runMenuItem});

    this.option1 = new Label();
    this.option1.Click += new EventHandler(this.optionClick);

    this.option2 = new Label();
    this.option2.Click += new EventHandler(this.optionClick);
}

void optionClick(object sender, EventArgs e)
{
    MouseEventArgs mea = e as MouseEventArgs;
    Control clicked = sender as Control;

    if(mea==null || clicked==null) return;

    if(mea.Button == MouseButtons.Right){
        this.contextMenuStrip.Show(clicked, mea.Location);
    }
}

void openMenuItemClick(object sender, EventArgs e)
{
    //Open stuff for option1 or option2, depending on which was right-clicked.
}

void runMenuItemClick(object sender, EventArgs e)
{
    //Run stuff for option1 or option2, depending on which was right-clicked.
}
Run Code Online (Sandbox Code Playgroud)

Tim*_*ine 5

在 runMenuItemClick 中,您需要将 sender 转换为 ToolStripMenuItem,然后将其所有者转换为 ContextMenuStrip。从那里您可以查看 ContextMenuStrip 的 SourceControl 属性以获取单击该项目的控件的名称。

void runMenuItemClick(object sender, EventArgs e) {
    var tsItem = ( ToolStripMenuItem ) sender;
    var cms = ( ContextMenuStrip ) tsItem.Owner;
    Console.WriteLine ( cms.SourceControl.Name );
}
Run Code Online (Sandbox Code Playgroud)