在menustrip c#中添加内容并指定其代码

时间:2014-05-19 03:43:34

标签: c# winforms visual-studio-2013

这类似于:How to add things to a menustrip programatically?,但我需要稍微不同的东西。

我有一个winform,我正在创建表单的新实例。但是,当我创建一个新表格时,我还会收集表单的所有当前实例,并填充一个" Window"带有menuitems的菜单让我关闭窗户。因此,我不仅需要以编程方式向menustrip添加内容,还需要指定这些菜单的功能。这可能吗?

代码:

    private void newWindowToolStripMenuItem_Click(object sender, EventArgs e)
    {
        var newForm = new Form1();
        newForm.Show();
        foreach (Form form in Application.OpenForms)
        {

            // add menu items under "Window" with the name of the window and the
            // event handler to close that window, aka form.Close() I assume; 
        }
    }

我想这样做,以便我更新" Window"菜单每次我创建一个新窗口,以便我关闭的窗口列表是准确的,没有任何奇怪的额外的东西。

2 个答案:

答案 0 :(得分:0)

您可以创建包含必填字段的类,并传递所需的数据。

public class MenuItemInfo
{
    public string Text { get; set; }
    public object Tag { get; set; }
    public EventHandler Handler { get; set; }
}

var menuItems = new List<MenuItemInfo>
{
    new MenuItemInfo
    {
        Text = "whatever",
        Tag = whatever,
        Handler = (o, s) =>
        {
            //Do whatever
        }
    }
};

ToolStripMenuItem toolStripMenuItem;
foreach (var mi in menuItems)
{
    ToolStripMenuItem foo = new ToolStripMenuItem(mi.Text);
    foo.Click += mi.Handler;
    foo.Tag = mi.Tag;

    toolStripMenuItem.DropDownItems.Add(foo);
}

答案 1 :(得分:0)

“ItemClicked” - 事件添加到ContexMenuStrip菜单中。 “ContextMenuStrip1”是此处使用的菜单的名称。编辑部分代码如下:

        var newForm = new Form1() { Name = "myForm" };
        newForm.Show();

        foreach (Form form in Application.OpenForms)
        {
            // Add new menuitem with the name of the form, and save the reference to "Tag"-property
            ToolStripMenuItem newItem = new ToolStripMenuItem() { Name = newForm.Name, Text = newForm.Name, Tag = newForm };

            // Add the new item to the menu
            contextMenuStrip1.Items.Add(newItem);
        }

然后点击“ItemClicked” -event:

    private void contextMenuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
    {

        // Close the linked form, if it isn't disposed
        if (!((Form)((ToolStripItem)e.ClickedItem).Tag).IsDisposed)
        {
            ((Form)((ToolStripItem)e.ClickedItem).Tag).Close();
        }

        // Remove this menuitem from the menu
        contextMenuStrip1.Items.Remove((ToolStripItem)e.ClickedItem);
    }