最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】C#中给TreeNode添加右键(Context Menu)

C# crifan 7354浏览 0评论

【背景】

现在想要给C#中的TreeNode添加右键菜单,

Add to Selection

Remove from Selection

两个菜单,

对任何一个TreeNode右键,都可以弹出此菜单。

【解决过程】

1.参考:

How to display a context menu that is specific to a selected TreeView node by using Visual C# .NET or Visual C# 2005

去添加ContextMenu,但是没有,只有ContextMenuStrip,只好先试试:

toolbox add contextmenustrip

但是结果觉得还不是太对。

2.参考:

C# winform treeview node添加右键菜单并选中节点

才想起来,别人:

How do I get the TreeNode that a context menu is called from?

中的那句:

tn.ContextMenu = GetContextMenu(state);
tv.Nodes.Add(tn);

比较靠谱。

所以自己去试试添加进来。

3.但是接着看到可以自己手动输入菜单项:

select contextmenustrip can input

4.经过一番折腾,现在可以点击TreeNode,然后出现右键菜单了:

(1)给项目中添加ContextMenuStrip

如下,去从工具栏中拖动一个ContextMenuStrip进来。此处改名为cmsSelection

(2)给ContextMenuStrip添加子菜单

A:右击cmsSelection->编辑项

right click contextmenustrip select edit

B:确保父级是cmsSelection,然后在其下,新建对应的子菜单

此处之前已有两个了:

old has two item

全部删除,然后重新建立2个子菜单:

item name is tsmiAddToSelection

其中,对应的此处,要注意Text改为你要的值,是用于显示出来菜单的名字:

tsmiAddToSelection text is Add To Selection

(3)然后,再去代码中,原先添加TreeNode到TreeView之前,设置此ContextMenuStrip:

TreeNode rootTreeNode = new TreeNode();
//rootTreeNode.Name = mainBrowserNode.Name;
rootTreeNode.Text = mainBrowserNode.Name;
rootTreeNode.Tag = mainBrowserNode;
rootTreeNode.ContextMenuStrip = cmsSelection;
trvCategoryTree.Nodes.Add(rootTreeNode);

(4)然后运行期间,右击任何TreeNode,即可显示出菜单了:

can show context menu

5.接下来,继续添加对应的每个子菜单所要执行的函数。

然后也基本搞懂了:

(1)去添加ContextMenuStrip的ItemClicked事件:

add ItemClicked event

(2)在ItemClicked中检测点击的是哪个Item

        private void cmsSelection_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            //MessageBox.Show(e.ClickedItem.Name + " cliked");
            MessageBox.Show(e.ClickedItem.Text + " cliked");
        }

然后就可以,添加对应的代码,去做自己想要做的事情了。

(3)运行时候的效果

can detect which item is cliked

 

【总结】

给TreeNode添加右键的总体的思路是:

1.添加ContextMenuStrip

2.在其下添加子菜单

3.实现ItemClicked事件,在其中判断点击了哪个子菜单,然后添加代码做你要做的事情即可。

转载请注明:在路上 » 【已解决】C#中给TreeNode添加右键(Context Menu)

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
82 queries in 0.158 seconds, using 22.12MB memory