变化
Color color = (e.State & TreeNodeStates.Selected) != 0 ?
SystemColors.HighlightText : SystemColors.WindowText;
到
Color color = (e.State & TreeNodeStates.Focused) != 0 ?
SystemColors.HighlightText : SystemColors.WindowText;
这在Vista X64和与2008年的.NET 3.5上起作用。让我知道它是否适合你。
在观察默认的Windows行为时,我观察到,在选择节点并获得焦点之前,文本和突出显示不会被绘制。所以我检查了聚焦条件以改变文本颜色。然而,这并不能精确地模拟寡妇的行为,因为在释放鼠标之前,新的颜色不会被使用。当它选择绘制蓝色高光状态时,它会显示出在OwnerDrawn模式下更改的点,而不是Windows绘制它时…这无疑是令人困惑的。
编辑
但是,当您创建自己的派生树视图时,您可以完全控制绘制所有内容的时间。
public class MyTreeView : TreeView
{
bool isLeftMouseDown = false;
bool isRightMouseDown = false;
public MyTreeView()
{
DrawMode = TreeViewDrawMode.OwnerDrawText;
}
protected override void OnMouseDown(MouseEventArgs e)
{
TrackMouseButtons(e);
base.OnMouseDown(e);
}
protected override void OnMouseUp(MouseEventArgs e)
{
TrackMouseButtons(e);
base.OnMouseUp(e);
}
protected override void OnMouseMove(MouseEventArgs e)
{
TrackMouseButtons(e);
base.OnMouseMove(e);
}
private void TrackMouseButtons(MouseEventArgs e)
{
isLeftMouseDown = e.Button == MouseButtons.Left;
isRightMouseDown = e.Button == MouseButtons.Right;
}
protected override void OnDrawNode(DrawTreeNodeEventArgs e)
{
// don't call the base or it will goof up your display!
// capture the selected/focused states
bool isFocused = (e.State & TreeNodeStates.Focused) != 0;
bool isSelected = (e.State & TreeNodeStates.Selected) != 0;
// set up default colors.
Color color = SystemColors.WindowText;
Color backColor = BackColor;
if (isFocused && isRightMouseDown)
{
// right clicking on a
color = SystemColors.HighlightText;
backColor = SystemColors.Highlight;
}
else if (isSelected && !isRightMouseDown)
{
// if the node is selected and we're not right clicking on another node.
color = SystemColors.HighlightText;
backColor = SystemColors.Highlight;
}
using (Brush sb = new SolidBrush(backColor))
e.Graphics.FillRectangle(sb,e.Bounds);
TextFormatFlags flags = TextFormatFlags.Left | TextFormatFlags.SingleLine |
TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis;
TextRenderer.DrawText(e.Graphics, e.Node.Text, Font, e.Bounds, color, backColor, flags);
}
}