Anton Semenov
Anton Semenov

Reputation: 6347

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!

Upvotes: 6

Views: 4383

Answers (1)

digEmAll
digEmAll

Reputation: 57220

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);
    }
}

Upvotes: 5

Related Questions