views:

301

answers:

1

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?

+2  A: 

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.

Hans Passant
Thanks! Great tip. Now works just as desired.
Good. Why don't you close the thread by marking it as answered.
Hans Passant
@nobugz: nice, something in Winforms you can't answer?
Sorin Comanescu