I have treeview and a context menu that is shown for every node. One node has the selection. I move now with the mouse to another node and open the context menu with a righ-mouse-click. Now there is the problem, that the selection is still on the old new node. How can I prevent, that the menu pops up, if the user haven't selected the node before by a mouse click selection ? In other words how can I achieve that the user must select the treenode before by a normal mouse click or the treenode gets the selection with the right mouse click automatically.
3 Answers
Try the following code, which provides you a preselection of the treenode.
TreeNode treeNodeAtMousePosition = this.treeView1.GetNodeAt(this.treeView1.PointToClient(Control.MousePosition));
TreeNode selectedTreeNode = this.treeView1.SelectedNode;
if (treeNodeAtMousePosition != null)
{
if (treeNodeAtMousePosition != selectedTreeNode)
treeView1.SelectedNode = treeNodeAtMousePosition;
}
Comments
The context menu has an event:
http://msdn.microsoft.com/en-us/library/ms229721.aspx
This is a cancellable event. In other words, test to see if you have a selected node and cancel the event if you don't - it will stop your menu from showing.
Comments
I created the context menu and assigned it to the TreeView control in the designer. Then I add the following code to the form
private TreeNode _rightclickedNode;
private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e) {
if (e.Button == MouseButtons.Right) {
_rightclickedNode = e.Node;
}
}
private void copyAsPathToolStripMenuItem1_Click(object sender, EventArgs e) {
Clipboard.SetText(_rightclickedNode.FullPath);
}