- 1 year ago
How to change Focused TreeNode Back Color in Treeview
To change the focused TreeNode's background color in a TreeView control, you can handle the DrawNode
event and customize the appearance of the focused node. Here's an example in C#:
csharpprivate void treeView1_DrawNode(object sender, DrawTreeNodeEventArgs e)
{
// Check if the node is focused
if ((e.State & TreeNodeStates.Focused) != 0)
{
// Set the background color for focused node
e.Graphics.FillRectangle(Brushes.LightBlue, e.Bounds);
// Set the text color for focused node
e.Graphics.DrawString(e.Node.Text, e.Node.TreeView.Font, Brushes.Black, e.Bounds);
}
else
{
// Use the default colors for other nodes
e.DrawDefault = true;
}
}
In this example, the treeView1_DrawNode
event handler is responsible for drawing the TreeView nodes. It checks if the node being drawn is in a focused state using the TreeNodeStates.Focused
flag. If it is focused, it sets a custom background color (in this case, LightBlue) and custom text color (Black) for the focused node. For other nodes, it uses the default drawing behavior by setting e.DrawDefault
to true
.
To use this event handler, you need to assign it to the DrawNode
event of the TreeView control. You can do this either in the designer by selecting the TreeView control, going to the Properties window, and locating the DrawNode
event, or programmatically by adding the following line of code in the form's constructor or Load
event:
csharptreeView1.DrawNode += treeView1_DrawNode;
Make sure to replace treeView1
with the actual name of your TreeView control.
With this approach, you can customize the appearance of the focused TreeNode by setting the background color and other visual properties to meet your requirements.