0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

c# TreeViewに右クリックイベントを登録する

Posted at

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

実行結果.png

0
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?