How to get the selected node of TreeView when context menu popup?

G

Guest

When user right click the tree node, a context menu popup. But I can not get
the node clicked calling TreeView.SelectedNode property correctly because the
default selection behavor of TreeView is left click.

How can I get the correct tree node when context menu popup?

Thanks.
 
M

Marc Scheuner [MVP ADSI]

When user right click the tree node, a context menu popup. But I can not get
the node clicked calling TreeView.SelectedNode property correctly because the
default selection behavor of TreeView is left click.

How can I get the correct tree node when context menu popup?

You could try to override the OnMouseDown event and determine the node
from the mouse position, and then pop up the context menu yourself,
something like that:

protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);

if (e.Button == MouseButtons.Right)
{
Point pt = new Point(e.X, e.Y);
this.PointToClient(pt);

TreeNode oCurrNode = this.GetNodeAt(pt);
if (oCurrNode == null)
return;

if (oCurrNode.Bounds.Contains(pt))
{
// pop up your context menu using the
// current tree node
}
}
}

Marc
================================================================
Marc Scheuner May The Source Be With You!
Berne, Switzerland m.scheuner -at- inova.ch
 
G

Guest

It's a useful way to implement the requirement. I thought the WinForms'
framework should support it directly. Is it a defect of .net framework?

Thanks Marc.
 
C

Claudio Grazioli

When user right click the tree node, a context menu popup. But I can not get
the node clicked calling TreeView.SelectedNode property correctly because the
default selection behavor of TreeView is left click.

How can I get the correct tree node when context menu popup?

Thanks.

Catch the MouseDown event of your treeview control. You can then check, if
it was the right mouse button. If so, get the TreeNode with GetNodeAt() and
then show the context menu.

private void _treeView_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
TreeNode node = _treeView.GetNodeAt(new Point(e.X, e.Y));
if (node != null)
{
// do something useful here
}
_treeContextMenu.Show(_treeView, new Point(e.X, e.Y));
}
}

Because you show the context menu manually this way, don't associate the
context menu with ContextMenu property of the treeview.

Let me know if it helped you.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top