简体   繁体   中英

TreeView node highlight colour in C#

Using Windows Forms , when I click on a TreeView node, the highlight colour is blue. Is there a way to change this?

It is possible if you create your own TreeView class and override the OnDrawNode method. For example, this one will highlight selected node with red color:

class ClassMyTreeView:TreeView
{
    public ClassMyTreeView()
    {
        this.DrawMode = TreeViewDrawMode.OwnerDrawText;
    }

    protected override void OnDrawNode(DrawTreeNodeEventArgs e)
    {
        TreeNodeStates state = e.State;
        Font font = e.Node.NodeFont ?? e.Node.TreeView.Font;
        Color fore = e.Node.ForeColor;
        if (fore == Color.Empty) 
            fore = e.Node.TreeView.ForeColor;
        if (e.Node == e.Node.TreeView.SelectedNode)
        {
            fore = SystemColors.HighlightText;
            e.Graphics.FillRectangle(new SolidBrush(Color.Red), e.Bounds);
            ControlPaint.DrawFocusRectangle(e.Graphics, e.Bounds, fore, Color.Red);
            TextRenderer.DrawText(e.Graphics, e.Node.Text, font, e.Bounds, fore, Color.Red, TextFormatFlags.GlyphOverhangPadding);
        }
        else
        {
            e.Graphics.FillRectangle(SystemBrushes.Window, e.Bounds);
            TextRenderer.DrawText(e.Graphics, e.Node.Text, font, e.Bounds, fore, TextFormatFlags.GlyphOverhangPadding);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM