禁用TreeView节点焦点提示

时间:2014-03-03 02:06:17

标签: c# winforms

我想知道如何在WinForms TreeView上禁用节点焦点矩形,我已经尝试过处理AfterSelect但是选择以及FocusCues仍然会出现一秒然后消失

代码

public class CustomTreeView : TreeView
{
    protected override void OnDrawNode(DrawTreeNodeEventArgs e)
    {
        e.DrawDefault = true;
        base.OnDrawNode(e);
    }

    protected override void OnAfterSelect(TreeViewEventArgs e)
    {
        SelectedNode = null;
        base.OnAfterSelect(e);
    }
}

1 个答案:

答案 0 :(得分:1)

我为你创建了一个示例类。它继承自TreeView类,并引入了新属性DrawElements。默认情况下,重点是rect&选择已启用。要禁用某些元素,请调整DrawElements属性的值。要同时禁用它们,请将其值设置为0

[Flags]
public enum TreeViewDrawElements
{
    FocusRect = 1,
    Selection = 2
}

public sealed class MyTreeView : TreeView
{
    public MyTreeView()
    {
        DrawMode = TreeViewDrawMode.OwnerDrawText;
        DrawElements = TreeViewDrawElements.FocusRect | TreeViewDrawElements.Selection;
    }

    [DefaultValue(TreeViewDrawElements.FocusRect | TreeViewDrawElements.Selection)]
    public TreeViewDrawElements DrawElements { get; set; }

    protected override void OnDrawNode(DrawTreeNodeEventArgs e)
    {
        base.OnDrawNode(e);
        if (DrawElements == (TreeViewDrawElements.FocusRect | TreeViewDrawElements.Selection))
        {
            e.DrawDefault = true;
            return;
        }
        TreeNode node = e.Node;
        Rectangle bounds = node.Bounds;
        Graphics g = e.Graphics;
        Size textSize = TextRenderer.MeasureText(node.Text, node.TreeView.Font);
        Point textLoc = new Point(bounds.X - 1, bounds.Y); // required to center the text 
        bounds = new Rectangle(textLoc, new Size(textSize.Width, bounds.Height));
        Font font = node.NodeFont ?? node.TreeView.Font;
        bool selected = (DrawElements & TreeViewDrawElements.Selection) != 0 && (e.State & TreeNodeStates.Selected) == TreeNodeStates.Selected;
        Color color = (selected && node.TreeView.Focused) ? SystemColors.HighlightText : (node.ForeColor != Color.Empty) ? node.ForeColor : node.TreeView.ForeColor;

        g.FillRectangle(selected ? SystemBrushes.Highlight : SystemBrushes.Window, bounds);
        if ((DrawElements & TreeViewDrawElements.FocusRect) != 0 && (e.State & TreeNodeStates.Selected) != 0)
            ControlPaint.DrawFocusRectangle(g, bounds, color, SystemColors.Highlight);
        TextRenderer.DrawText(g, e.Node.Text, font, bounds, color, TextFormatFlags.Default);
    }
}

用法示例:

MyTreeView tree = new MyTreeView { DrawElements = TreeViewDrawElements.Selection };
tree.Nodes.Add("aaa");
tree.Nodes.Add("bbb");
tree.Nodes.Add("ccc");