-TreeView のアイテムを右クリックした場合にポップアップメニューを表示する。
using System;
using System.Windows.Forms;
using System.Drawing;
class FormMain : Form {
private TreeView menuTreeView;
private ContextMenuStrip docMenu;
[STAThread]
public static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run( new FormMain());
}
FormMain()
{
InitializeMenuTreeView();
}
public void contextMenuStrip_SubMenuClick(object sender, EventArgs e)
{
string s = ((ToolStripMenuItem)sender).Text;
MessageBox.Show("Item is " + s, "Item Clicke");
}
public void InitializeMenuTreeView()
{
// Create the TreeView.
menuTreeView = new TreeView();
menuTreeView.Size = new Size(200, 200);
// Create the root node.
TreeNode docNode = new TreeNode("Documents");
// Add some additional nodes.
docNode.Nodes.Add("phoneList.doc");
docNode.Nodes.Add("resume.doc");
// Add the root nodes to the TreeView.
menuTreeView.Nodes.Add(docNode);
// Create the ContextMenuStrip.
docMenu = new ContextMenuStrip();
//Create some menu items.
ToolStripMenuItem openLabel = new ToolStripMenuItem();
openLabel.Text = "Open";
ToolStripMenuItem deleteLabel = new ToolStripMenuItem();
deleteLabel.Text = "Delete";
ToolStripMenuItem renameLabel = new ToolStripMenuItem();
renameLabel.Text = "Rename";
openLabel.Click += contextMenuStrip_SubMenuClick;
deleteLabel.Click += contextMenuStrip_SubMenuClick;
renameLabel.Click += contextMenuStrip_SubMenuClick;
//Add the menu items to the menu.
docMenu.Items.AddRange(new ToolStripMenuItem[]{openLabel,
deleteLabel, renameLabel});
// Set the ContextMenuStrip property to the ContextMenuStrip.
docNode.ContextMenuStrip = docMenu;
// Add the TreeView to the form.
this.Controls.Add(menuTreeView);
}
}