C# 用于多个控件的Windows窗体右键单击菜单

C# 用于多个控件的Windows窗体右键单击菜单,c#,winforms,C#,Winforms,我在Windows窗体中有几个控件,我希望右键单击每个控件时弹出相同的菜单。但是,操作应根据单击的控件略有不同 我遇到的问题是ToolStripMenuItem没有关于最初单击哪个控件以使工具栏可见的任何信息。我真的不想每个控件都需要一个单独的上下文菜单 到目前为止,我的代码看起来像: private void InitializeComponent() { this.openMenuItem = new ToolStripMenuItem(); this.openMenuIte

我在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.
}

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

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

我想;这种方法会造成问题;当项目具有快捷方式时(例如:CTRL+X)