C#TreeView节点选中后失去焦点时改变节点背景色
在使用TreeView控件时候,单击一个节点,当鼠标聚焦到别的地方的时候,之前点击的这个节点就看不清楚了
举例截图
单击后 聚焦离开后
问题解决后:
单击后: 鼠标离开后
参考:http://www.cnblogs.com/shuang121/archive/2013/05/28/3103225.html
解决办法:
初始化窗体完成后绑定事件
private void init()
{ this.treeView1.HideSelection = false;
//自已绘制
this.treeView1.DrawMode = TreeViewDrawMode.OwnerDrawText;
this.treeView1.DrawNode += new DrawTreeNodeEventHandler(treeView1_DrawNode);
}
绘制颜色
/// <summary>
/// 绘制颜色
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void treeView1_DrawNode(object sender, DrawTreeNodeEventArgs e)
{
e.DrawDefault = true; //我这里用默认颜色即可,只需要在TreeView失去焦点时选中节点仍然突显
return;
//or 自定义颜色
if ((e.State & TreeNodeStates.Selected) != )
{
//演示为绿底白字
e.Graphics.FillRectangle(Brushes.DarkBlue, e.Node.Bounds); Font nodeFont = e.Node.NodeFont;
if (nodeFont == null) nodeFont = ((TreeView)sender).Font;
e.Graphics.DrawString(e.Node.Text, nodeFont, Brushes.White, Rectangle.Inflate(e.Bounds, , ));
}
else
{
e.DrawDefault = true;
} if ((e.State & TreeNodeStates.Focused) != )
{
using (Pen focusPen = new Pen(Color.Black))
{
focusPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot;
Rectangle focusBounds = e.Node.Bounds;
focusBounds.Size = new Size(focusBounds.Width - ,
focusBounds.Height - );
e.Graphics.DrawRectangle(focusPen, focusBounds);
}
} }