如何在winforms中改变树视图中热跟踪的前景色?

时间:2015-01-28 12:42:23

标签: c# winforms treeview

enter image description here

我有一个具有黑白主题的winforms应用程序。我有一个树视图,其背景颜色设置为黑色,文本显示为白色。我已将hotTracking设置为true。现在按照以下MSDN链接: https://msdn.microsoft.com/en-us/library/system.windows.forms.treeview.hottracking.aspx

  

HotTracking属性设置为true时,每个树节点标签   当鼠标指针经过时,它呈现出超链接的外观   超过它。下划线字体样式应用于Font和   ForeColor设置为蓝色,使标签显示为链接。该   外观不受用户的互联网设置控制   操作系统。

似乎前色被硬编码为蓝色。但这会在我的应用程序中产生问题,如附带的示例图像所示。由于这种蓝色,文本在黑色背景上变得不可读。虽然我可以禁用热跟踪,但客户需要它。有没有办法克服热追踪的前色。

以下是我用于将主题应用于树视图的示例代码:

this.trvUsers.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;            
this.trvUsers.FullRowSelect = true;
this.trvUsers.HideSelection = false;
this.trvUsers.HotTracking = true;            
this.trvUsers.ShowLines = false;
this.treeView1.BackColor = System.Drawing.Color.Black;
this.treeView1.ForeColor = System.Drawing.Color.White;

1 个答案:

答案 0 :(得分:2)

您应该处理TreeView的DrawNode事件。更多信息请访问:TreeView.DrawNode Event

    private void Form1_Load(object sender, EventArgs e)
    {
        this.treeView1.Nodes.Add("Node1");
        this.treeView1.Nodes.Add("Node2");
        this.treeView1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
        this.treeView1.FullRowSelect = true; this.treeView1.HideSelection = false; 
        this.treeView1.HotTracking = true;
        this.treeView1.ShowLines = false;
        this.treeView1.BackColor = System.Drawing.Color.Black; 

        this.treeView1.DrawMode = TreeViewDrawMode.OwnerDrawText;
        this.treeView1.DrawNode += treeView1_DrawNode;
    }

    private void treeView1_DrawNode(object sender, DrawTreeNodeEventArgs e)
    {
        Font font = e.Node.NodeFont ?? e.Node.TreeView.Font;
        Color foreColor = e.Node.ForeColor;

        if (e.State == TreeNodeStates.Hot)
        {
            foreColor = Color.Red;
        }
        else
        {
            foreColor = Color.White;
        }

        TextRenderer.DrawText(e.Graphics, e.Node.Text, font, e.Bounds, foreColor, Color.Black, TextFormatFlags.GlyphOverhangPadding);            
    }