[英]add things to menustrip c# and specify their code
這類似於: 如何以編程方式向菜單欄添加內容? ,但我需要一些不同的東西。
我有一個winform,正在創建該窗體的新實例。 但是,當我創建一個新窗體時,我還將收集該窗體的所有當前實例,並使用菜單項填充“窗口”菜單以允許我關閉窗口。 因此,我不僅需要以編程方式向菜單欄添加內容,還需要指定這些菜單的功能。 那可能嗎?
碼:
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;
}
}
我想這樣做,以便每次創建新窗口時都更新“窗口”菜單,以便要關閉的窗口列表准確無誤。
您可以創建帶有必填字段的類,並傳遞必填數據。
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);
}
將“ ItemClicked” -event添加到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”事件:
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.