TreeView.DrawNode 事件

定義

在描繪 TreeView 而且 DrawMode 屬性設定為 Normal 以外的 TreeViewDrawMode 值時發生。

public:
 event System::Windows::Forms::DrawTreeNodeEventHandler ^ DrawNode;
public event System.Windows.Forms.DrawTreeNodeEventHandler DrawNode;
public event System.Windows.Forms.DrawTreeNodeEventHandler? DrawNode;
member this.DrawNode : System.Windows.Forms.DrawTreeNodeEventHandler 
Public Custom Event DrawNode As DrawTreeNodeEventHandler 

事件類型

範例

下列程式碼範例示範如何使用擁有者繪圖來自訂 TreeView 控制項。 範例 TreeView 中的控制項會顯示選擇性節點標籤以及標準節點標籤。 節點標籤是使用 TreeNode.Tag 屬性來指定。 控制項 TreeView 也會使用自訂色彩,其中包含自訂醒目提示色彩。

您可以藉由設定色彩屬性來自訂大部分 TreeView 的色彩,但選取範圍醒目提示色彩無法當做屬性使用。 此外,預設選取範圍醒目提示矩形只會在節點標籤周圍延伸。 擁有者繪圖必須用來繪製節點標籤,並繪製足以包含節點標籤的自訂醒目提示矩形。

在此範例中 DrawNode ,事件的處理常式會手動繪製節點標籤和自訂選取範圍醒目提示。 未選取的節點不需要自訂。 針對這些屬性, DrawTreeNodeEventArgs.DrawDefault 屬性會設定 true 為 ,讓作業系統繪製它們。

此外,事件的處理常式 MouseDown 會提供點擊測試。 根據預設,節點只能按一下其標籤周圍的區域來選取。 MouseDown如果存在,事件處理常式會選取在此區域內或節點標籤周圍區域中按一下的節點。

#using <System.dll>
#using <System.Windows.Forms.dll>
#using <System.Drawing.dll>

using namespace System;
using namespace System::Drawing;
using namespace System::Windows::Forms;
public ref class TreeViewOwnerDraw: public Form
{
private:
   TreeView^ myTreeView;

   // Create a Font object for the node tags.
   System::Drawing::Font^ tagFont;

public:

   TreeViewOwnerDraw()
   {
      tagFont = gcnew System::Drawing::Font( "Helvetica",8,FontStyle::Bold );

      // Create and initialize the TreeView control.
      myTreeView = gcnew 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 += gcnew DrawTreeNodeEventHandler( this, &TreeViewOwnerDraw::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 += gcnew MouseEventHandler( this, &TreeViewOwnerDraw::myTreeView_MouseDown );
      
      // Initialize the form and add the TreeView control to it.
      this->ClientSize = System::Drawing::Size( 292, 273 );
      this->Controls->Add( myTreeView );
   }

protected:
   // Clean up any resources being used.        
   ~TreeViewOwnerDraw()
   {
      if ( tagFont != nullptr )
      {
         delete tagFont;
      }
   }

   // 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) != (TreeNodeStates)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.
         System::Drawing::Font^ nodeFont = e->Node->NodeFont;
         if ( nodeFont == nullptr )
                  nodeFont = (dynamic_cast<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 != nullptr )
      {
         e->Graphics->DrawString( e->Node->Tag->ToString(), tagFont, Brushes::Yellow, (float)e->Bounds.Right + 2, (float)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) != (TreeNodeStates)0 )
      {
         Pen^ focusPen = gcnew Pen( Color::Black );
         try
         {
            focusPen->DashStyle = System::Drawing::Drawing2D::DashStyle::Dot;
            Rectangle focusBounds = NodeBounds( e->Node );
            focusBounds.Size = System::Drawing::Size( focusBounds.Width - 1, focusBounds.Height - 1 );
            e->Graphics->DrawRectangle( focusPen, focusBounds );
         }
         finally
         {
            if ( focusPen )
               delete safe_cast<IDisposable^>(focusPen);
         }

      }
   }

   // Selects a node that is clicked on its label or tag text.
   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.
   Rectangle NodeBounds( TreeNode^ node )
   {
      // Set the return value to the normal node bounds.
      Rectangle bounds = node->Bounds;
      if ( node->Tag != nullptr )
      {
         // 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->~Graphics();
      }

      return bounds;
   }
};

[STAThreadAttribute]
int main()
{
   Application::Run( gcnew TreeViewOwnerDraw );
}
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;
    }
}
Imports System.Drawing
Imports System.Windows.Forms

Public Class TreeViewOwnerDraw
    Inherits Form

    Private WithEvents myTreeView As TreeView
    
    ' Create a Font object for the node tags.
    Private tagFont As New Font("Helvetica", 8, FontStyle.Bold)
    
    Public Sub New()

        ' 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.
        Dim node As TreeNode
        Dim x As Integer
        For x = 1 To 3

            ' Add a root node to the TreeView control.
            node = myTreeView.Nodes.Add(String.Format("Task {0}", x))
            Dim y As Integer
            For y = 1 To 3 

                ' Add a child node to the root node.
                node.Nodes.Add(String.Format("Subtask {0}", y))
            Next y
        Next x
        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.
        myTreeView.DrawMode = TreeViewDrawMode.OwnerDrawText

        ' 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.
        AddHandler myTreeView.MouseDown, AddressOf myTreeView_MouseDown
        
        ' Initialize the form and add the TreeView control to it.
        Me.ClientSize = New Size(292, 273)
        Me.Controls.Add(myTreeView)
    End Sub
    
    <STAThreadAttribute()> _
    Shared Sub Main()
        Application.Run(New TreeViewOwnerDraw())
    End Sub
    
    ' Draws a node.
    Private Sub myTreeView_DrawNode(ByVal sender As Object, _
        ByVal e As DrawTreeNodeEventArgs) Handles myTreeView.DrawNode

        ' Draw the background and node text for a selected node.
        If (e.State And TreeNodeStates.Selected) <> 0 Then

            ' 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.
            Dim nodeFont As Font = e.Node.NodeFont
            If nodeFont Is Nothing Then
                nodeFont = CType(sender, TreeView).Font
            End If

            ' Draw the node text.
            e.Graphics.DrawString(e.Node.Text, nodeFont, Brushes.White, _
                e.Bounds.Left - 2, e.Bounds.Top)

        ' Use the default background and node text.
        Else
            e.DrawDefault = True
        End If

        ' If a node tag is present, draw its string representation 
        ' to the right of the label text.
        If (e.Node.Tag IsNot Nothing) Then
            e.Graphics.DrawString(e.Node.Tag.ToString(), tagFont, _
                Brushes.Yellow, e.Bounds.Right + 2, e.Bounds.Top)
        End If

        ' 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 And TreeNodeStates.Focused) <> 0 Then
            Dim focusPen As New Pen(Color.Black)
            Try
                focusPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot
                Dim focusBounds As Rectangle = NodeBounds(e.Node)
                focusBounds.Size = New Size(focusBounds.Width - 1, _
                    focusBounds.Height - 1)
                e.Graphics.DrawRectangle(focusPen, focusBounds)
            Finally
                focusPen.Dispose()
            End Try
        End If

    End Sub

    ' Selects a node that is clicked on its label or tag text.
    Private Sub myTreeView_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs)
        Dim clickedNode As TreeNode = myTreeView.GetNodeAt(e.X, e.Y)
        If NodeBounds(clickedNode).Contains(e.X, e.Y) Then
            myTreeView.SelectedNode = clickedNode
        End If
    End Sub

    ' Returns the bounds of the specified node, including the region 
    ' occupied by the node label and any node tag displayed.
    Private Function NodeBounds(ByVal node As TreeNode) As Rectangle

        ' Set the return value to the normal node bounds.
        Dim bounds As Rectangle = node.Bounds
        If (node.Tag IsNot Nothing) Then

            ' Retrieve a Graphics object from the TreeView handle
            ' and use it to calculate the display width of the tag.
            Dim g As Graphics = myTreeView.CreateGraphics()
            Dim tagWidth As Integer = CInt(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()
        End If
        Return bounds
    End Function 'NodeBounds

End Class

備註

使用此事件,使用擁有者繪圖自訂控制項中的 TreeView 節點外觀。

只有當 屬性設定為 TreeViewDrawModeOwnerDrawText 的值 OwnerDrawAll 時, DrawMode 才會引發這個事件。 下表指出 TreeNode 當 屬性設定為這些值時 DrawMode ,如何自訂 。

DrawMode 屬性值 TreeNode 自訂
OwnerDrawText 您可以自訂卷 TreeNode 標區域。 所有其他 TreeNode 元素都會自動繪製。
OwnerDrawAll 您可以自訂整個 TreeNode 的外觀。 如有需要,就必須手動繪製節點的圖示、核取方塊、加號和減號,以及連接節點的線條。

TreeNode.Text如果使用控制項 Font 的 屬性所 TreeView 指定的字型繪製值,則該值會佔用的區域,就是可以按一下節點來選取它的區域。 這稱為點擊測試區域。 如果您繪製在此區域之外,您應該提供自己的程式碼,以在按一下節點的可見區域時選取節點。

使用 時 OwnerDrawText ,點擊測試區域會對應至 DrawTreeNodeEventArgs.Bounds 屬性。 不過,使用 OwnerDrawAll 時, DrawTreeNodeEventArgs.Bounds 屬性會包含 的 TreeView 整個寬度。 在此情況下,您可以取得 DrawTreeNodeEventArgs.Node 值並存取其 TreeNode.Bounds 屬性,以存取點擊測試區域。 然後,您可以在這些界限內繪製節點的點擊測試區域,或者您可以提供自己的點擊測試程式碼。 請注意,設定 TreeNode.NodeFont 屬性不會變更點擊測試區域的大小,這會使用針對整個 TreeView 指定的字型來計算。

如需如何處理事件的詳細資訊,請參閱 處理和引發事件

適用於

另請參閱