Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unselectable node in TreeView

I have TreeView control on winform. I desire to make several nodes unselectable. How can I achive this.
There is only one idea in my mind - custom drawn nodes, but may be more easier way exists? Please advice me

I have already try such code in BeforeSelect event handler:

private void treeViewServers_BeforeSelect(object sender, TreeViewCancelEventArgs e)
{
  if (e.Node.Parent != null)
  {
    e.Cancel = true;
  }
}

But effect it gained is not appropriate. Node temporary get selection when I am holding left mouse button on it.

Thanks in advance!

like image 874
Anton Semenov Avatar asked Apr 06 '11 11:04

Anton Semenov


People also ask

How do you select a node in TreeView?

Selected = true; The node for which the property is set gets selected as shown below. Furthermore, you can also select a node at runtime by right-clicking it. This is the default behavior of TreeView.

What is TreeView node?

The Nodes property holds a collection of TreeNode objects, each of which has a Nodes property that can contain its own TreeNodeCollection. This nesting of tree nodes can make it difficult to navigate a tree structure, but the FullPath property makes it easier to determine your location within the tree structure.


1 Answers

You could completely disable mouse events in case you click on a not-selectable node.

To do this, you have to override TreeView a shown in the following code

public class MyTreeView : TreeView
{
    int WM_LBUTTONDOWN = 0x0201; //513
    int WM_LBUTTONUP = 0x0202; //514
    int WM_LBUTTONDBLCLK = 0x0203; //515

    protected override void WndProc(ref Message m)
    {
        if (m.Msg == WM_LBUTTONDOWN ||
           m.Msg == WM_LBUTTONUP ||
           m.Msg == WM_LBUTTONDBLCLK)
        {
            //Get cursor position(in client coordinates)
            Int16 x = (Int16)m.LParam;
            Int16 y = (Int16)((int)m.LParam >> 16);

            // get infos about the location that will be clicked
            var info = this.HitTest(x, y);

            // if the location is a node
            if (info.Node != null)
            {
                // if is not a root disable any click event
                if(info.Node.Parent != null)
                    return;//Dont dispatch message
            }
        }

        //Dispatch as usual
        base.WndProc(ref m);
    }
}
like image 117
digEmAll Avatar answered Sep 28 '22 06:09

digEmAll