TreeView captures focus Ctrl + Click

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

Currently, it works as we would like if I open another form in the DoubleClick handler (and double-click on the node, obviously); however, if I use the Click handler (or MouseClick) and open another form when I press the control key, it correctly opens another form, but returns focus to the original form.

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

+3
source share
1 answer

TreeView steals focus back after the event returns. Very annoying. You can use the trick: to 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 is triggered as soon as all events for the TreeView have completed and your program enters standby mode and re-enters the message loop.

+7
source

Source: https://habr.com/ru/post/1703569/


All Articles