Is there an easy way to have a selected TreeNode retain its SystemColors.Highlight BackColor while the TreeView doesn't have focus? Because even with HideSelection set to false, the selected BackColor is near impossible to see.
Selected TreeNode while TreeView has focus:
Selected TreeNode while TreeView does not have focus:
Thanks in advance.
EDIT: I'm aware i could set DrawMode to OwnerDrawAll and then add a custom DrawNode event. I did attempt this previously, the problem i have is i don't know how to go about drawing the TreeNode's corresponding ImageKey properly.
Solution 1Use TreeView. SelectedNode[^] property, which get or set selected node for currently selected Treeview. If no TreeNode is currently selected, the SelectedNode property is a null reference (Nothing in Visual Basic).
The TreeView allows you to edit nodes by setting the allowEditing property to true. To directly edit the nodes in place, double click the TreeView node or select the node and press F2 key. When editing is completed by focus out or by pressing the Enter key, the modified node's text saves automatically.
If retaining the SystemColors.Highlight
background color is all you wanted, then you don't need to set the TreeView
's DrawMode
property to TreeViewDrawMode.OwnerDrawAll
. Setting it to TreeViewDrawMode.OwnerDrawText
should be sufficient, thus you don't need to worry about drawing the TreeNode
's corresponding ImageKey
.
Set the TreeView.DrawMode
to TreeViewDrawMode.OwnerDrawText
:
treeView.DrawMode = TreeViewDrawMode.OwnerDrawText;
Set the Treview.HideSelection
to false
, so that the node states will be kept as selected:
treeView.HideSelection= false;
Add DrawNode
event handler to draw the background using SystemColors.Highlight
color:
private void treeView_DrawNode(object sender, DrawTreeNodeEventArgs e) { if (e.Node == null) return; // if treeview's HideSelection property is "True", // this will always returns "False" on unfocused treeview var selected = (e.State & TreeNodeStates.Selected) == TreeNodeStates.Selected; var unfocused = !e.Node.TreeView.Focused; // we need to do owner drawing only on a selected node // and when the treeview is unfocused, else let the OS do it for us if (selected && unfocused) { var font = e.Node.NodeFont ?? e.Node.TreeView.Font; e.Graphics.FillRectangle(SystemBrushes.Highlight, e.Bounds); TextRenderer.DrawText(e.Graphics, e.Node.Text, font, e.Bounds, SystemColors.HighlightText, TextFormatFlags.GlyphOverhangPadding); } else { e.DrawDefault = true; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With