TreeView.DrawNode イベントとは? わかりやすく解説

TreeView.DrawNode イベント

メモ : このイベントは、.NET Framework version 2.0新しく追加されたものです。

TreeView が描画され、DrawMode プロパティNormal 以外の TreeViewDrawMode 値に設定されているときに発生します

名前空間: System.Windows.Forms
アセンブリ: System.Windows.Forms (system.windows.forms.dll 内)
構文構文

Public Event DrawNode As
 DrawTreeNodeEventHandler
Dim instance As TreeView
Dim handler As DrawTreeNodeEventHandler

AddHandler instance.DrawNode, handler
public event DrawTreeNodeEventHandler DrawNode
public:
event DrawTreeNodeEventHandler^ DrawNode {
    void add (DrawTreeNodeEventHandler^ value);
    void remove (DrawTreeNodeEventHandler^ value);
}
/** @event */
public void add_DrawNode (DrawTreeNodeEventHandler
 value)

/** @event */
public void remove_DrawNode (DrawTreeNodeEventHandler
 value)
JScript では、イベント使用できますが、新規に宣言することはできません。
解説解説

このイベントは、オーナー描画使用してTreeView コントロール内のノード外観カスタマイズするために使用します

このイベントは、DrawMode プロパティTreeViewDrawMode 値が OwnerDrawAll または OwnerDrawText に設定されている場合にだけ発生します次の表では、DrawMode プロパティがこれらの値に設定されているときに、TreeNode をどのようにカスタマイズできるのかを示します

TreeNode.Text の値が TreeView コントロールFont プロパティ指定されフォント使用して描画される場合、その値が表示される領域は、クリックしたときにノード選択される領域です。これはヒット テスト領域呼ばれます。この領域以外の場所に値を描画する場合ノード表示領域クリックされたときにそのノード選択するための独自のコード記述する必要があります

ヒット テスト領域は、OwnerDrawText使用する場合、DrawTreeNodeEventArgs.Bounds プロパティ対応します。ただし、OwnerDrawAll使用する場合は、DrawTreeNodeEventArgs.Bounds プロパティTreeView 全体の幅を囲む境界表します。この場合ヒット テスト領域アクセスするには、DrawTreeNodeEventArgs.Node の値を取得し、その TreeNode.Bounds プロパティアクセスます。その上で、これらの境界内にノードヒット テスト領域描画するか、独自のヒット テスト コードを定義できます。TreeNode.NodeFont プロパティ設定しても、ヒット テスト領域サイズ変化しません。ヒット テスト領域サイズは、TreeView 全体に対して指定されフォント使用して計算されます。

イベント処理詳細については、「イベント利用」を参照してください

使用例使用例

オーナー描画使用して TreeView コントロールカスタマイズする方法次のコード例示します。例で使用されている TreeView コントロールは、通常のノード ラベルのそばに、オプションノード タグ表示しますノード タグは、TreeNode.Tag プロパティ使用して指定されます。TreeView コントロールは、カスタム強調表示色を含むカスタム カラー使用します

TreeView の色の大半は、カラー プロパティ設定してカスタマイズできますが、選択内容強調表示する色については、プロパティとしてアクセスすることはできません。また、選択項目を強調表示する既定四角形は、ノード ラベル周囲についてのみ拡張されます。ノード タグ描画したり、ノード タグ全体表示できるようにカスタマイズされた強調表示用の四角形描画したりするには、オーナー描画使用する必要があります

この例では、DrawNode イベントハンドラが、ノード タグおよびカスタム選択項目の強調表示手動描画ます。選択されないノードは、カスタマイズの必要はありません。これらのノードについては、DrawTreeNodeEventArgs.DrawDefault プロパティtrue設定しオペレーティング システムによって描画されるようにします。

さらに、MouseDown イベントハンドラヒット テスト行います既定では、ノード選択されるのは、ラベル周辺領域クリックされたときだけです。MouseDownイベント ハンドラは、この領域内、またはノード タグがある場合その周辺領域内の任意の場所がクリックされたときに、ノード選択します

Imports System
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 'New
    
    <STAThreadAttribute()> _
    Shared Sub Main()
        Application.Run(New TreeViewOwnerDraw())
    End Sub 'Main
    
    ' 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 Not (e.Node.Tag Is
 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 'myTreeView_DrawNode

    ' 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 'myTreeView_MouseDown

    ' 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 Not (node.Tag Is
 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 '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;
        
    }

}
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 
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照



英和和英テキスト翻訳>> Weblio翻訳
英語⇒日本語日本語⇒英語
  

辞書ショートカット

すべての辞書の索引

「TreeView.DrawNode イベント」の関連用語

TreeView.DrawNode イベントのお隣キーワード
検索ランキング

   

英語⇒日本語
日本語⇒英語
   



TreeView.DrawNode イベントのページの著作権
Weblio 辞書 情報提供元は 参加元一覧 にて確認できます。

   
日本マイクロソフト株式会社日本マイクロソフト株式会社
© 2024 Microsoft.All rights reserved.

©2024 GRAS Group, Inc.RSS