在TreeView中右键选择Node,并弹出自定义上下文菜单

在网络上SS到一篇如何在TreeView控件的节点上进行自定义右键功能.自己正好也对这方面进行欠缺于是做了一遍,结合这位兄弟的帖子自己再加强一次.

前提控件使用:TreeView控件+ContextMenu控件

 

        private void contextmenu_Click(object sender, EventArgs e)
        {
            MenuItem item = sender as MenuItem;
            if (item != null)
            {
                if ("Properties" == item.Text)
                {
                    MessageBox.Show("abc");//可以是具体的事件名称
                }
                if ("Run" == item.Text)
                {
                    MessageBox.Show("ddd");//可以是具体的事件名称
                }
            }
        }

        private void treeView1_MouseUp(object sender, MouseEventArgs e)
        {
            TreeView treev = sender as TreeView;
            Point point = treev.PointToClient(Cursor.Position);
            TreeViewHitTestInfo info = treev.HitTest(point.X, point.Y);
            TreeNode node = info.Node;

            if (node != null && MouseButtons.Right == e.Button)
            {
                treev.SelectedNode = node;

                //开始说明

                //以下可以定义成一个统一的,如何获取定义的名字可以自定义一个方法
                if ("节点0" == node.Name)
                {
                    this.contextMenu.MenuItems.Clear();
                    this.contextMenu.MenuItems.Add("Add To Scan List");
                    this.contextMenu.MenuItems.Add("Run");
                    this.contextMenu.MenuItems.Add("-");
                    this.contextMenu.MenuItems.Add("Delete");
                    for (int i = 0; i < this.contextMenu.MenuItems.Count; i++)
                    {
                        this.contextMenu.MenuItems[i].Click += new EventHandler(contextmenu_Click);
                    }
                    treev.ContextMenu = this.contextMenu;
                }
                else if ("节点1" == node.Name)
                {
                    this.contextMenu.MenuItems.Clear();
                    this.contextMenu.MenuItems.Add("Properties");
                    this.contextMenu.MenuItems.Add("-");
                    this.contextMenu.MenuItems.Add("Delete");
                    for (int i = 0; i < this.contextMenu.MenuItems.Count; i++)
                    {
                        this.contextMenu.MenuItems[i].Click += new EventHandler(contextmenu_Click);
                    }
                    treev.ContextMenu = this.contextMenu;
                }
                else
                {
                    this.contextMenu.MenuItems.Clear();
                    treev.ContextMenu = null;
                }

                contextMenu.Show(treev, point);
                this.contextMenu.MenuItems.Clear();

                //结束说明
            }
        }

你可能感兴趣的:(list,网络,object,properties,null,delete)