Export (0) Print
Expand All

DrawTreeNodeEventArgs Class

Provides data for the DrawNode event.

Namespace: System.Windows.Forms
Assembly: System.Windows.Forms (in system.windows.forms.dll)

public class DrawTreeNodeEventArgs : EventArgs
public class DrawTreeNodeEventArgs extends EventArgs
public class DrawTreeNodeEventArgs extends EventArgs
Not applicable.

Use the DrawNode event to customize the appearance of nodes in a TreeView control using owner drawing.

The DrawNode event is raised by a TreeView control when its TreeView.DrawMode property is set to TreeViewDrawMode.OwnerDrawAll or TreeViewDrawMode.OwnerDrawText and a node is displayed or updated. The DrawTreeNodeEventArgs passed to the event handler contains information about the node to draw as well as providing methods to help you draw the node.

Use the State or Node properties to retrieve information about the node to draw. Use the Graphics property to do the actual drawing within the area specified by the Bounds property. To make the operating system draw a node that does not need to be owner drawn, set the DrawDefault property to true.

When the TreeView.DrawMode property is set to TreeViewDrawMode.OwnerDrawText, the area indicated by the Bounds property includes the label portion of the node only. When the TreeView.DrawMode property is set to TreeViewDrawMode.OwnerDrawAll, the Bounds area includes the entire node, including the area typically used for icons, checkboxes, plus and minus signs, and lines connecting the nodes.

The following code example demonstrates how to customize a TreeView control using owner drawing. The TreeView control in the example displays optional node tags alongside the standard node labels. Node tags are specified using the TreeNode.Tag property. The TreeView control also uses custom colors, including a custom highlight color.

You can customize most of the TreeView colors by setting color properties, but the selection highlight color is not available as a property. Additionally, the default selection highlight rectangle extends only around a node label. Owner drawing must be used to draw the node tags and to draw a customized highlight rectangle large enough to include a node tag.

In the example, a handler for the TreeView.DrawNode event draws the node tags and the custom selection highlight manually. Unselected nodes do not need customization. For these, the DrawDefault property is set to true so that they will be drawn by the operating system.

Additionally, a handler for the Control.MouseDown event provides hit-testing. By default, a node can be selected only by clicking the region around its label. The Control.MouseDown event handler selects a node that is clicked anywhere within this region or within the region around a node tag, if present.

using System;
using System.Drawing;
using System.Windows.Forms;

public class TreeViewOwnerDraw : Form
{
    private TreeView myTreeView;

    // Create a Font object for the node tags.
    Font tagFont = new Font("Helvetica", 8, FontStyle.Bold);

    public TreeViewOwnerDraw()
    {
        // Create and initialize the TreeView control.
        myTreeView = new TreeView();
        myTreeView.Dock = DockStyle.Fill;
        myTreeView.BackColor = Color.Tan;
        myTreeView.CheckBoxes = true;

        // Add nodes to the TreeView control.
        TreeNode node;
        for (int x = 1; x < 4; ++x)
        {
            // Add a root node to the TreeView control.
            node = myTreeView.Nodes.Add(String.Format("Task {0}", x));
            for (int y = 1; y < 4; ++y)
            {
                // Add a child node to the root node.
                node.Nodes.Add(String.Format("Subtask {0}", y));
            }
        }
        myTreeView.ExpandAll();

        // Add tags containing alert messages to a few nodes 
        // and set the node background color to highlight them.
        myTreeView.Nodes[1].Nodes[0].Tag = "urgent!";
        myTreeView.Nodes[1].Nodes[0].BackColor = Color.Yellow;
        myTreeView.SelectedNode = myTreeView.Nodes[1].Nodes[0];
        myTreeView.Nodes[2].Nodes[1].Tag = "urgent!";
        myTreeView.Nodes[2].Nodes[1].BackColor = Color.Yellow;

        // Configure the TreeView control for owner-draw and add
        // a handler for the DrawNode event.
        myTreeView.DrawMode = TreeViewDrawMode.OwnerDrawText;
        myTreeView.DrawNode += 
            new DrawTreeNodeEventHandler(myTreeView_DrawNode);

        // Add a handler for the MouseDown event so that a node can be 
        // selected by clicking the tag text as well as the node text.
        myTreeView.MouseDown += new MouseEventHandler(myTreeView_MouseDown);

        // Initialize the form and add the TreeView control to it.
        this.ClientSize = new Size(292, 273);
        this.Controls.Add(myTreeView);
    }

    // Clean up any resources being used.        
    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            tagFont.Dispose();
        }
        base.Dispose(disposing);
    }

    [STAThreadAttribute()]
    static void Main() 
    {
        Application.Run(new TreeViewOwnerDraw());
    }

    // Draws a node.
    private void myTreeView_DrawNode(
        object sender, DrawTreeNodeEventArgs e)
    {
        // Draw the background and node text for a selected node.
        if ((e.State & TreeNodeStates.Selected) != 0)
        {
            // Draw the background of the selected node. The NodeBounds
            // method makes the highlight rectangle large enough to
            // include the text of a node tag, if one is present.
            e.Graphics.FillRectangle(Brushes.Green, NodeBounds(e.Node));

            // Retrieve the node font. If the node font has not been set,
            // use the TreeView font.
            Font nodeFont = e.Node.NodeFont;
            if (nodeFont == null) nodeFont = ((TreeView)sender).Font;

            // Draw the node text.
            e.Graphics.DrawString(e.Node.Text, nodeFont, Brushes.White,
                Rectangle.Inflate(e.Bounds, 2, 0));
        }

        // Use the default background and node text.
        else 
        {
            e.DrawDefault = true;
        }

        // If a node tag is present, draw its string representation 
        // to the right of the label text.
        if (e.Node.Tag != null)
        {
            e.Graphics.DrawString(e.Node.Tag.ToString(), tagFont,
                Brushes.Yellow, e.Bounds.Right + 2, e.Bounds.Top);
        }

        // If the node has focus, draw the focus rectangle large, making
        // it large enough to include the text of the node tag, if present.
        if ((e.State & TreeNodeStates.Focused) != 0)
        {
            using (Pen focusPen = new Pen(Color.Black))
            {
                focusPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot;
                Rectangle focusBounds = NodeBounds(e.Node);
                focusBounds.Size = new Size(focusBounds.Width - 1, 
                focusBounds.Height - 1);
                e.Graphics.DrawRectangle(focusPen, focusBounds);
            }
        }
    }

    // Selects a node that is clicked on its label or tag text.
    private void myTreeView_MouseDown(object sender, MouseEventArgs e)
    {
        TreeNode clickedNode = myTreeView.GetNodeAt(e.X, e.Y);
        if (NodeBounds(clickedNode).Contains(e.X, e.Y))
        {
            myTreeView.SelectedNode = clickedNode;
        }
    }

    // Returns the bounds of the specified node, including the region 
    // occupied by the node label and any node tag displayed.
    private Rectangle NodeBounds(TreeNode node)
    {
        // Set the return value to the normal node bounds.
        Rectangle bounds = node.Bounds;
        if (node.Tag != null)
        {
            // Retrieve a Graphics object from the TreeView handle
            // and use it to calculate the display width of the tag.
            Graphics g = myTreeView.CreateGraphics(); 
            int tagWidth = (int)g.MeasureString
                (node.Tag.ToString(), tagFont).Width + 6;

            // Adjust the node bounds using the calculated value.
            bounds.Offset(tagWidth/2, 0);
            bounds = Rectangle.Inflate(bounds, tagWidth/2, 0);
            g.Dispose();
         }
        
        return bounds;
        
    }

}

import System.*;
import System.Drawing.*;
import System.Windows.Forms.*;

public class TreeViewOwnerDraw extends Form
{
    private TreeView myTreeView;

    // Create a Font object for the node tags.
    private Font tagFont = new Font("Helvetica", 8, FontStyle.Bold);

    public TreeViewOwnerDraw()
    {
        // Create and initialize the TreeView control.
        myTreeView = new TreeView();
        myTreeView.set_Dock(DockStyle.Fill);
        myTreeView.set_BackColor(Color.get_Tan());
        myTreeView.set_CheckBoxes(true);
        // Add nodes to the TreeView control.
        TreeNode node;
        for (int x = 1; x < 4; ++x) {
            // Add a root node to the TreeView control.
            node = myTreeView.get_Nodes().Add(String.Format("Task {0}",
                (Int32)x));
            for (int y = 1; y < 4; ++y) {
                // Add a child node to the root node.
                node.get_Nodes().Add(String.Format("Subtask {0}", (Int32)y));
            }
        }
        myTreeView.ExpandAll();
        // Add tags containing alert messages to a few nodes 
        // and set the node background color to highlight them.
        myTreeView.get_Nodes().get_Item(1).get_Nodes().get_Item(0).
            set_Tag("urgent!");
        myTreeView.get_Nodes().get_Item(1).get_Nodes().get_Item(0).
            set_BackColor(Color.get_Yellow());
        myTreeView.set_SelectedNode(myTreeView.get_Nodes().get_Item(1).
            get_Nodes().get_Item(0));
        myTreeView.get_Nodes().get_Item(2).get_Nodes().get_Item(1).
            set_Tag("urgent!");
        myTreeView.get_Nodes().get_Item(2).get_Nodes().get_Item(1).
            set_BackColor(Color.get_Yellow());

        // Configure the TreeView control for owner-draw and add
        // a handler for the DrawNode event.
        myTreeView.set_DrawMode(TreeViewDrawMode.OwnerDrawText);
        myTreeView.add_DrawNode(new DrawTreeNodeEventHandler(
            myTreeView_DrawNode));
        // Add a handler for the MouseDown event so that a node can be 
        // selected by clicking the tag text as well as the node text.
        myTreeView.add_MouseDown(new MouseEventHandler(myTreeView_MouseDown));
        // Initialize the form and add the TreeView control to it.
        this.set_ClientSize(new Size(292, 273));
        this.get_Controls().Add(myTreeView);
    } //TreeViewOwnerDraw

    // Clean up any resources being used.        
    protected void Dispose(boolean disposing)
    {
        if (disposing) {
            tagFont.Dispose();
        }
        super.Dispose(disposing);
    } //Dispose

    /** @attribute STAThreadAttribute()
     */
    public static void main(String[] args)
    {
        Application.Run(new TreeViewOwnerDraw());
    } //main

    // Draws a node.
    private void myTreeView_DrawNode(Object sender, DrawTreeNodeEventArgs e)
    {
        // Draw the background and node text for a selected node.
        if ((int)(e.get_State() & TreeNodeStates.Selected) != 0) {
            // Draw the background of the selected node. The NodeBounds
            // method makes the highlight rectangle large enough to
            // include the text of a node tag, if one is present.
            e.get_Graphics().FillRectangle(Brushes.get_Green(),
                NodeBounds(e.get_Node()));
            // Retrieve the node font. If the node font has not been set,
            // use the TreeView font.
            Font nodeFont = e.get_Node().get_NodeFont();
            if (nodeFont == null) {
                nodeFont = ((TreeView)sender).get_Font();
            }
            // Draw the node text.
            e.get_Graphics().DrawString(e.get_Node().get_Text(),
                nodeFont, Brushes.get_White(),
                RectangleF.op_Implicit(Rectangle.Inflate(e.get_Bounds(), 2, 0)));
        }
        // Use the default background and node text.
        else {
            e.set_DrawDefault(true);
        }
        // If a node tag is present, draw its string representation 
        // to the right of the label text.
        if (e.get_Node().get_Tag() != null) {
            e.get_Graphics().DrawString(e.get_Node().get_Tag().ToString(),
                tagFont, Brushes.get_Yellow(), e.get_Bounds().get_Right() + 2,
                e.get_Bounds().get_Top());
        }
        // If the node has focus, draw the focus rectangle large, making
        // it large enough to include the text of the node tag, if present.
        if ((int)(e.get_State() & TreeNodeStates.Focused) != 0) { 
            Pen focusPen = new Pen(Color.get_Black());
            try {
                focusPen.set_DashStyle(System.Drawing.Drawing2D.DashStyle.Dot);
                Rectangle focusBounds = NodeBounds(e.get_Node());
                focusBounds.set_Size(new Size(focusBounds.get_Width() - 1,
                    focusBounds.get_Height() - 1));
                e.get_Graphics().DrawRectangle(focusPen, focusBounds);
            }
            finally {
                focusPen.Dispose();
            }            
        }
    } //myTreeView_DrawNode

    // Selects a node that is clicked on its label or tag text.
    private void myTreeView_MouseDown(Object sender, MouseEventArgs e)
    {
        TreeNode clickedNode = myTreeView.GetNodeAt(e.get_X(), e.get_Y());
        if (NodeBounds(clickedNode).Contains(e.get_X(), e.get_Y())) {
            myTreeView.set_SelectedNode(clickedNode);
        }
    } //myTreeView_MouseDown

    // Returns the bounds of the specified node, including the region 
    // occupied by the node label and any node tag displayed.
    private Rectangle NodeBounds(TreeNode node)
    {
        // Set the return value to the normal node bounds.
        Rectangle bounds = node.get_Bounds();
        if (node.get_Tag() != null) {
            // Retrieve a Graphics object from the TreeView handle
            // and use it to calculate the display width of the tag.
            Graphics g = myTreeView.CreateGraphics();
            int tagWidth = (int)(g.MeasureString(node.get_Tag().ToString(),
                tagFont).get_Width()) + 6;
            // Adjust the node bounds using the calculated value.
            bounds.Offset(tagWidth / 2, 0);
            bounds = Rectangle.Inflate(bounds, tagWidth / 2, 0);
            g.Dispose();
        }
        return bounds;
    } //NodeBounds
} //TreeViewOwnerDraw 

System.Object
   System.EventArgs
    System.Windows.Forms.DrawTreeNodeEventArgs

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows 98, Windows Server 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The Microsoft .NET Framework 3.0 is supported on Windows Vista, Microsoft Windows XP SP2, and Windows Server 2003 SP1.

.NET Framework

Supported in: 3.0, 2.0

Community Additions

ADD
Show:
© 2014 Microsoft