I have used the mouse down event of the treeview control. And I want to set the selected node as the node on which the mouse down event has h开发者_运维问答appened. How can this problem be resolved?
The MouseDown
event is fired before the node is selected. Try handling the AfterSelect
event instead. If e.Action
is set to TreeViewAction.ByMouse
then the event was raised by the mouse.
A couple of options come to mind here. Both might well be overkill, but they still solve the problem.
Handle the
MouseDown
event and use theHitTest
method to determine which node the user clicked on. If they clicked on a valid node, manually set the focus to that node via theSelectedNode
property.private void myTreeView_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Right) { myTreeView.SelectedNode = myTreeView.HitTest(e.Location).Node; } }
The bazooka-style solution is to override the
WndProc
method and listen forWM_RBUTTONDOWN
messages. I've done this in my own extended version of theTreeView
control because it allows me to fix some really minor stuff that normal, non-obsessive people probably wouldn't notice. I go into excruciating detail in my answer here.Basically, you're doing the same thing as the code above does, but at a lower level, which stops the native control from pulling some shenanigans with the focus. I don't remember if they actually apply here (hence the potential overkill), but I'm too lazy to fire up Visual Studio to see for sure.
public class FixedTreeView : System.Windows.Forms.TreeView { protected override void WndProc(ref System.Windows.Forms.Message m) { const int WM_RBUTTONDOWN = 0x204; if (m.Msg == WM_RBUTTONDOWN) { Point mousePos = this.PointToClient(Control.MousePosition); this.SelectedNode = this.GetNodeAt(mousePos); } base.WndProc(ref m); } }
The first method should work just fine for you. Try that before breaking out bigger weapons.
精彩评论