TreeView re-grabs focus on Ctrl+Click

一世执手 提交于 2019-12-30 06:57:05

问题


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.



来源:https://stackoverflow.com/questions/569673/treeview-re-grabs-focus-on-ctrlclick

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!