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         }  

源代码工程文件下载

 

posted @ 2017-04-11 14:46  JiYF  阅读(7330)  评论(0编辑  收藏  举报