2011-04-06 101 views
5

我在winform上有TreeView控件。我希望使几个节点不可选。我怎样才能实现这一点。
在我的脑海里只有一个想法 - 自定义绘制节点,但可能更简单的方式存在?请咨询我树视图中的不可选节点

我已经在BeforeSelect事件处理程序尝试这样的代码:

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

但影响它获得是不恰当的。当我按住鼠标左键时,节点临时获取选择。

在此先感谢!

回答

4

如果您点击不可选节点,则可以完全禁用鼠标事件。

要做到这一点,你必须覆盖TreeView在下面的代码

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

大的显示!我也为右键添加过滤,现在我的树视图完美地工作!非常感谢你! – 2011-04-06 12:50:10

+1

如果用户使用键盘(上,下,左,右)键选择节点会怎么样 – Thunder 2012-05-16 10:43:03

+4

我的文章中的代码只是在鼠标单击时取消选择,而不是由问题中的代码处理。但是对于键盘按键选择,就足以在treeViewServers_BeforeSelect事件中取消事件(如果覆盖它,则在OnBeforeSelect中)。当然,你需要结合两个代码才能完全避免选择。 – digEmAll 2012-05-16 12:05:30