2011-04-06 99 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