Find node clicked under context menu - c#

How can I find out which node in a tree list the context menu has been activated? For instance right-clicking a node and selecting an option from the menu.
I can't use the TreeViews' SelectedNode property because the node is only been right-clicked and not selected.

You can add a mouse click event to the TreeView, then select the correct node using GetNodeAt given the mouse coordinates provided by the MouseEventArgs.
void treeView1MouseUp(object sender, MouseEventArgs e)
{
if(e.Button == MouseButtons.Right)
{
// Select the clicked node
treeView1.SelectedNode = treeView1.GetNodeAt(e.X, e.Y);
if(treeView1.SelectedNode != null)
{
myContextMenuStrip.Show(treeView1, e.Location);
}
}
}

Here is my solution. Put this line into NodeMouseClick event of the TreeView:
((TreeView)sender).SelectedNode = e.Node;

I find the standard windows treeview behavior selection behavior to be quite annoying. For example, if you are using Explorer and right click on a node and hit Properties, it highlights the node and shows the properties dialog for the node you clicked on. But when you return from the dialog, the highlighted node was the node previously selected/highlighted before you did the right-click. I find this causes usability problems because I am forever being confused on whether I acted on the right node.
So in many of our GUIs, we change the selected tree node on a right-click so that there is no confusion. This may not be the same as a standard iwndos app like Explorer (and I tend to strongly model our GUI behavior after standard window apps for usabiltiy reasons), I believe that this one exception case results in far more usable trees.
Here is some code that changes the selection during the right click:
private void tree_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
{
// only need to change selected note during right-click - otherwise tree does
// fine by itself
if ( e.Button == MouseButtons.Right )
{
Point pt = new Point( e.X, e.Y );
tree.PointToClient( pt );
TreeNode Node = tree.GetNodeAt( pt );
if ( Node != null )
{
if ( Node.Bounds.Contains( pt ) )
{
tree.SelectedNode = Node;
ResetContextMenu();
contextMenuTree.Show( tree, pt );
}
}
}
}

Reviving this question because I find this to be a much better solution.
I use the NodeMouseClick event instead.
void treeview_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
if( e.Button == MouseButtons.Right )
{
tree.SelectedNode = e.Node;
}
}

This is a very old question, but I still found it useful. I am using a combination of some of the answers above, because I don't want the right-clicked node to become the selectedNode. If I have the root node selected and want to delete one of it's children, I don't want the child selected when I delete it (I am also doing some work on the selectedNode that I don't want to happen on a right-click). Here is my contribution:
// Global Private Variable to hold right-clicked Node
private TreeNode _currentNode = new TreeNode();
// Set Global Variable to the Node that was right-clicked
private void treeView_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Right)
_currentNode = e.Node;
}
// Do something when the Menu Item is clicked using the _currentNode
private void toolStripMenuItem_Clicked(object sender, EventArgs e)
{
if (_currentNode != null)
MessageBox.Show(_currentNode.Text);
}

Similar to Marcus' answer, this was the solution I found worked for me:
private void treeView_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
treeView.SelectedNode = treeView.GetNodeAt(e.Location);
}
}
You need not show the context menu yourself if you set it to each individual node like so:
TreeNode node = new TreeNode();
node.ContextMenuStrip = contextMenu;
Then inside the ContextMenu's Opening event, the TreeView.SelectedNode property will reflect the correct node.

If you want the context menu to be dependent on the selected item you're best move I think is to use Jonesinator's code to select the clicked item. Your context menu content can then be dependent on the selected item.
Selecting the item first as opposed to just using it for the context menu gives a few advantages. The first is that the user has a visual indication as to which he clicked and thus which item the menu is associated with. The second is that this way it's a hell of a lot easier to keep compatible with other methods of invoking the context menu (e.g. keyboard shortcuts).

Here is how I do it.
private void treeView_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Right)
e.Node.TreeView.SelectedNode = e.Node;
}

Another option you could run with is to have a global variable that has the selected node. You would just need to use the TreeNodeMouseClickEventArgs.
public void treeNode_Click(object sender, TreeNodeMouseClickEventArgs e)
{
_globalVariable = e.Node;
}
Now you have access to that node and it's properties.

I would like to propose an alternative to using the click events, using the context menu's Opened event:
private void Handle_ContextMenu_Opened(object sender, EventArgs e)
{
TreeViewHitTestInfo info = treeview.HitTest(treeview.PointToClient(Cursor.Position));
TreeNode contextNode;
// was there a node where the context menu was opened?
if (info != null && info.Node != null)
{
contextNode = info.Node;
}
// Set the enabled states of the context menu elements
menuEdit.Enabled = contextNode != null;
menuDelete.Enabled = contextNode != null;
}
This has the following advantages that I can see:
It does not change the selected node
No separate event handler needed to store the target node instance
Can disable menu items if the user right-clicks empty space in the TreeView
Note: if you worry that the user may have already moved the mouse by the time the menu is opened, it is possible to use the Opening event instead.

Related

how to check a check box in tree-view when a tree-view node is selected / clicked in c#

in c# windows application i have a tree view with different nodes associated with Check Box for each node(this is for multiple Node Selection). how to change the Check Box property to checked when we click on respective node?
private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
TreeNode node = e.Node;
node.Checked = true;
}
Try this event ...

Right Click to select items in a ListBox

I'm trying to make a list of items that you can do several actions with by right-clicking and having a context menu come up. I've completed that, no problem whatsoever.
But I'd like to have it so that when you right click on a item, instead of leaving the current item selected, to select the item the mouse is over.
I've researched this and other related questions, and I've tried to use indexFromPoint (which I found through my research) but whenever I right click on a item, it always just clears the selected item and doesn't show the context menu, as I have it set so that it wont appear if there is no selected item.
Here is the code I'm currently using:
ListBox.SelectedIndex = ListBox.IndexFromPoint(Cursor.Position.X, Cursor.Position.Y);
Handle ListBox.MouseDown and select the item in there. Like this:
private void listBox1_MouseDown(object sender, MouseEventArgs e)
{
listBox1.SelectedIndex = listBox1.IndexFromPoint(e.X, e.Y);
}
this one is working...
this.ListBox.MouseUp += new System.Windows.Forms.MouseEventHandler(this.List_RightClick);
private void List_RightClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
int index = this.listBox.IndexFromPoint(e.Location);
if (index != ListBox.NoMatches)
{
listBox.Items[index];
}
}
}
Can also get same behaviour by setting a MouseRightButtonUp event on the whole listbox then:
private void AccountItemsT33_OnMouseRightButtonUp(object sender, MouseButtonEventArgs e)
{
// If have selected an item via left click, then do a right click, need to disable that initial selection
AccountItemsT33.SelectedIndex = -1;
VisualTreeHelper.FindElementsInHostCoordinates(e.GetPosition(null), (sender as ListBox)).OfType<ListBoxItem>().First().IsSelected = true;
}

Which object was the chosen option from ContextMenuStrip

I make windows form application. I have on form TreeView, I add few nodes and add ContextMenuStrip.
var menu = new ContextMenuStrip();
menu.Items.Add("Some text", new Bitmap(1, 1), new EventHandler(function_name));
var treeView = new TreeView(..);
treeView.ContextMenuStrip = menu;
treeView.Nodes.Add(new TreeNode()
{
...
Tag = someObject
});
My problems is how can I check in function function_name on which treeNode was clicked and chosen option from ContextMenuStrip
edit
function_name sygnature
public void pokaz_DoubleClick(object sender, EventArgs e)
{
}
You can handle the TreeNodeMouseClick event. In your TreeNodeMouseClickEventHandler you will have access to a TreeNodeMouseClickEventArgs argument. This argument contains a number of properties you can use to check which mouse button was clicked on which node. For example.
private TreeNode rightClickeNode;
void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
rightClickedNode = e.Node;
}
}
You can then access rightClickedNode from your function_name.
what is the signature of the function_name method?
generally you can check the content of the sender parameter but it could happen it is the TreeView and not the TreeNode, if so you can check the properties of the e parameter.
Another way is that at every mouse down you make sure you select the node under the mouse in the TreeView so when function_name executes you get your node taking treeview.SelectedNode
You can make the node selected right before the Context Menu is shown and then you just need to check the SelectedNode property. Something like this:
private void treeView_MouseDown(object sender, MouseEventArgs e)
{
//See what node is at the location that was just clicked
var clickedNode = treeView.GetNodeAt(e.Location);
//Make that node the selected node
treeView.SelectedNode = clickedNode;
}
private void function_name(object sender, EventArgs e)
{
var currentNode = treeView.SelectedNode;
//Do something with currentNode
}

TreeNode Selection Problems in C#

Whenever I click outside the tree nodes text, on the control part, it tigers a node click event- but doesn't highlight the node. I am unsure why this is happening.
I want the node to be selected on a click- when you click the nodes text- not the whitespace- I only assume that the nodes width reaches across the whole Treenode? I have the Treeview on dock.fill mode if that has something to do with it- I tried everything but can't get it to behave correctly.
Maybe someone will know what's going on.
Update:
if (e.Location.IsEmpty)
{
Seems to work better- but still selects the node in the blank place where there is no text- Obviously the node width extends across the whole treeview it seems?
Is there a better way to accomplish what I want? Or is that the best way?
UPDATE: Previous idea isn't working- sigh- I thought it did it but it didn't.
New Problem : I think part of the problem is related to the focus now when I switch from treeview.
UPDATE-
The only code I came up with about disabling right mouse click to select node on beforeSelect event is
if (MouseButtons == System.Windows.Forms.MouseButtons.Right)
{
e.Cancel = true;
}
But it didn't work- any help is appreciated- following suggestions of only answer, for more details.
You should use the treeView.HitTest method to determine which part of the node has been clicked.
private bool IsClickOnText(TreeView treeView, TreeNode node, Point location)
{
var hitTest = treeView1.HitTest(location);
return hitTest.Node == node
&& hitTest.Location == TreeViewHitTestLocations.Label;
}
private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
if(IsClickOnText(treeView1, e.Node, e.Location))
{
MessageBox.Show("click");
}
}
private void treeView1_BeforeSelect(object sender, TreeViewCancelEventArgs e)
{
if (e.Action == TreeViewAction.ByMouse)
{
var position = treeView1.PointToClient(Cursor.Position);
e.Cancel = !IsClickOnText(treeView1, e.Node, position);
}
}
Use the .AfterSelect and/or .BeforeSelect events to handle the selection processing instead of the .Click event. Then it will select the node only when you click on the text, and it won't fire .AfterSelect or .BeforeSelect when you click on the white space.

How can i find selected node of treeview when click right button

I m working on windows project and using c#. I want to catch treeview selected node which i click that by right click.
I'm writing tvlocation.SelectedNode.Index
but it return only Root Node's index.
Thanks for your helps...
If you are looking to identify the node that was clicked on, then handle the NodeMouseClick event, as follows:
private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
MessageBox.Show(string.Format("Node clicked: {0}", e.Node.Text));
}
}
You could select the node programatically here, if you need that too.

Categories

Resources