Thursday, April 12, 2012

TreeView - Checkbox (double click) - workaround

Windows - Forms - TreeView - C#

While working on TreeView implementation came across a strange issue.
Double click is event is not been properly called w.r.t. check box associated with node.

Following are the scenario that has been observed:

  • TreeView does not fire DoubleClick event the very first time.
  • TreeView may fire DoubleClick event when a user only single clicks.
  • TreeView does not fire BeforeCheck/AfterCheck events at all when user double clicks the checkbox image.
This is something Microsoft need to figure it out.

Disable the double click event from firing in TreeView so that unreliable functionality can be taken out.
Only click event will be allowed and as far as end user will find no issue with double click and single click.

Step 1:
Build you application with all the relevant functionality.

Step 2:
In Form.Designer.cs file add following code at end.
Inheriting TreeView class and suppressing the double click (WM_LBUTTONDBLCLK message) in derived class. Then derived class is being used for processing.

namespace System.Windows.Forms
    public class TestTreeView : TreeView
        protected override void WndProc(ref Message m)
            if (m.Msg == 0x203) // identified double click
                m.Result = IntPtr.Zero;
                base.WndProc(ref m);

Step 3:
In Form.Designer.cs file change references of TreeView class with inherited class TestTreeView.
private void InitializeComponent()
     this.tvBaseDirectory = new System.Windows.Forms.TestTreeView();

Step 4: