C#TreeView節點選中后失去焦點時改變節點背景色


C#TreeView節點選中后失去焦點時改變節點背景色

在使用TreeView控件時候,單擊一個節點,當鼠標聚焦到別的地方的時候,之前點擊的這個節點就看不清楚了

舉例截圖

單擊后                                                                                          聚焦離開后

問題解決后:

單擊后:                                鼠標離開后

參考:http://www.cnblogs.com/shuang121/archive/2013/05/28/3103225.html

解決辦法:

初始化窗體完成后綁定事件

1  private void init()
2         {
3           
4             this.treeView1.HideSelection = false;
5             //自已繪制  
6             this.treeView1.DrawMode = TreeViewDrawMode.OwnerDrawText;
7             this.treeView1.DrawNode += new DrawTreeNodeEventHandler(treeView1_DrawNode);
8         }

繪制顏色

 1  /// <summary>
 2         /// 繪制顏色
 3         /// </summary>
 4         /// <param name="sender"></param>
 5         /// <param name="e"></param>
 6         private void treeView1_DrawNode(object sender, DrawTreeNodeEventArgs e)
 7         {
 8             e.DrawDefault = true; //我這里用默認顏色即可,只需要在TreeView失去焦點時選中節點仍然突顯  
 9             return;
10             //or  自定義顏色  
11             if ((e.State & TreeNodeStates.Selected) != 0)
12             {
13                 //演示為綠底白字  
14                 e.Graphics.FillRectangle(Brushes.DarkBlue, e.Node.Bounds);
15 
16                 Font nodeFont = e.Node.NodeFont;
17                 if (nodeFont == null) nodeFont = ((TreeView)sender).Font;
18                 e.Graphics.DrawString(e.Node.Text, nodeFont, Brushes.White, Rectangle.Inflate(e.Bounds, 2, 0));
19             }
20             else
21             {
22                 e.DrawDefault = true;
23             }
24 
25             if ((e.State & TreeNodeStates.Focused) != 0)
26             {
27                 using (Pen focusPen = new Pen(Color.Black))
28                 {
29                     focusPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot;
30                     Rectangle focusBounds = e.Node.Bounds;
31                     focusBounds.Size = new Size(focusBounds.Width - 1,
32                     focusBounds.Height - 1);
33                     e.Graphics.DrawRectangle(focusPen, focusBounds);
34                 }
35             }
36 
37         }  

源代碼工程文件下載

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM