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

时间:2011-04-19 19:09:50

标签: 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.
}

1 个答案:

答案 0 :(得分:4)

在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 );
}