TreeView re-grabs focus on Ctrl+Click

2019-02-14 18:49发布

问题:

I have a WinForms TreeView control that I would like to use to open another form based on which node is currently selected. I want to open that other form when I Ctrl+Click on the node.

Currently, it works the way I would like if I open the other form in a DoubleClick handler (and double-click on the node, obviously); however, if I use a Click (or MouseClick) handler and open the other form when the Control key is pressed, it opens the other form correctly but returns focus to the original form.

How do I keep focus from returning to the original form (I do still want to keep it open) after opening the other form? Why is there different behavior between the Click and DoubleClick handlers?

回答1:

TreeView steals the focus back after the event returns. Very annoying. You can use a trick: delay the action of the event with Control.BeginInvoke:

private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e) {
  this.BeginInvoke(new TreeNodeMouseClickEventHandler(delayedClick), sender, e);
}
private void delayedClick(object sender, TreeNodeMouseClickEventArgs e) {
  // Now do your thing...
}

The delayedClick method runs as soon as all the events for the TreeView have finished running and your program goes idle and re-enters the message loop.