日期:2014-05-19  浏览次数:21030 次

ContextMenuStrip弹出的问题!急~~~
比如我建立了一个TreeView窗口,里边有aa和bb两项,我想在aa或bb上点击右键时弹出右键菜单,点击TreeView控键的空白处时不弹出,
也就是说怎么给TreeView里的项添加ContextMenuStrip右键菜单,就象系统里的任务管理器一样,点击项会出现菜单!谢谢!!

------解决方案--------------------
要捕捉mousedown事件,通过GetNodeAt函数获取所在节点
在popup事件里看看有没有当前节点,如果节点为空就不弹出

------解决方案--------------------
// Declare the TreeView and ContextMenuStrip
private TreeView menuTreeView;
private ContextMenuStrip docMenu;

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 ";

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

------解决方案--------------------
以下代码调试通过:

private void Form1_Load(object sender, EventArgs e)
{
TreeNode tn1 = new TreeNode( "所有 ");
TreeNode aa = new TreeNode( "aa ");
aa.ContextMenuStrip = this.contextMenuStrip1;

TreeNode bb = new TreeNode( "bb ");
bb.ContextMenuStrip = this.contextMenuStrip1;

tn1.Nodes.Add(aa);
tn1.Nodes.Add(bb);

tn1.ExpandAll();
this.treeView1.Nodes.Add(tn1);
}
------解决方案--------------------
楼上的注意:
“点击TreeView控键的空白处时不弹出”,你那样子点空白照样会出来菜单

加在右键菜单根本都不需要写代码,直接设计时指定TreeView的contexMenu属性就可以

关键是弹出问题
private void tv_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
if(e.Button == MouseButtons.Right)
{
tv.SelectedNode = tv.GetNodeAt (e.X ,e.Y );
}
}

private void ccm_Popup(object sender, System.EventArgs e)
{
bool NotNull=(tv.SelectedNode!=null);
具体菜单项的.Visible=NotNull;
}

------解决方案--------------------
类似GetNodeAt之类的函数在很多控件中都可以找到
------解决方案--------------------
不错,mark
------解决方案--------------------
搞定就结贴贝...

让LS几位等.你好意思吗???

哈哈