WinForm中设置TreeView选中节点的颜色

848 查看


TreeView

TreeView没有属性可以设置选中节点颜色,因此只有在DrawNode事件中来改变颜色。

首先设置TreeView的属性

treeView1.DrawMode = TreeViewDrawMode.OwnerDrawText;

DrawNode事件

        private void treeView1_DrawNode(object sender, DrawTreeNodeEventArgs e)
        {
            if ((e.State & TreeNodeStates.Selected) != 0)
            {
                e.Graphics.FillRectangle(Brushes.Red, 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, 2, 0));
            }
            else
            {
                e.DrawDefault = true;
            }
        }

END