Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change background color of selected node in TreeView using TreeViewDrawMode.OwnerDrawAll?

Tags:

c#

.net

winforms

I need to change back colours of selected nodes, when node selected and has focus - back color make green, when selected but doesn't have focus - red. I can't make the difference between selected node with focus on tree view and without. Tree view located in TabPage object.

//...
this.myTreeView.HideSelection = false;
//...
private void myTreeView_drawNode(object sender, DrawTreeNodeEventArgs e)
{
      Color backColorSelected = System.Drawing.Color.Green;
      Color backColor = System.Drawing.Color.Red;
      // node selected and has focus
      if (((e.State & TreeNodeStates.Selected) != 0) 
      && (this.myTabControl.Focused)) // this doesn't work, node is always red
      {
          using (SolidBrush brush = new SolidBrush(backColorSelected))
          {
              e.Graphics.FillRectangle(brush, e.Bounds);
          }
      }
      // node selected but doesn't have focus
      else if ((e.State & TreeNodeStates.Selected) != 0)
      {
          using (SolidBrush brush = new SolidBrush(backColor))
          {
             e.Graphics.FillRectangle(brush, e.Bounds);
          }
      }
      // not selected at all
      else
      {
          e.Graphics.FillRectangle(Brushes.White, e.Bounds);
      }

      e.Graphics.DrawRectangle(SystemPens.Control, e.Bounds);

      TextRenderer.DrawText(e.Graphics,
                             e.Node.Text,
                             e.Node.TreeView.Font,
                             e.Node.Bounds,
                             e.Node.ForeColor);
}   
like image 668
Romz Avatar asked Oct 07 '22 08:10

Romz


1 Answers

Just check the node's property, it works (tested). Also I suggest caching any custom brushes you make like the following.. (Of course you can also use Brushes.Red and Brushes.Green)

SolidBrush greenBrush = new SolidBrush(Color.Green);
    SolidBrush redBrush = new SolidBrush(Color.Red);

    private void myTreeView_drawNode(object sender, DrawTreeNodeEventArgs e)
    {
        if (e.Node.IsSelected)
        {
            if (treeView1.Focused)
                e.Graphics.FillRectangle(greenBrush, e.Bounds);
            else
                e.Graphics.FillRectangle(redBrush, e.Bounds);
        }
        else
            e.Graphics.FillRectangle(Brushes.White, e.Bounds);

        e.Graphics.DrawRectangle(SystemPens.Control, e.Bounds);

        TextRenderer.DrawText(e.Graphics,
                               e.Node.Text,
                               e.Node.TreeView.Font,
                               e.Node.Bounds,
                               e.Node.ForeColor);
    }

P.S. You'll probably need to render something that you click to expand nodes etc.

like image 141
Alan Avatar answered Oct 10 '22 05:10

Alan