Monday, July 31, 2006

Using a ContextMenuStrip with a TreeView, my approach

Mike Hillyer posted an entry on his blog that was very useful to me.

I've implemented the same basic thing, but I think I did it in a way that is a little cleaner, and saves some cycles. There are two catches with Mike's implementation: 1) is that the TreeView MouseClick event is fired anytime you click anywhere in the TreeView; not just on a node. 2) is that you can't cancel the action. Users expect to be able to cancel a mouse event by holding down the mouse button, and moving the mouse off of the control. (you can experiment with this yourself. Open any MSFT program, and click-hold on an ok button. Then drag off the button, and let go of the mouse. The ok will not happen).

Rather than catch the MouseDown event, I am catching the NodeMouseClick event. That only fires when a node gets clicked, and the event args include a reference to the node that was clicked. Since it's a mouse click event, it honors the drag off the control to cancel idea.

Here's the code:


private void tvMachines_NodeMouseClick(object sender,
TreeNodeMouseClickEventArgs e)
{
tvMachines.SelectedNode = e.Node;
}