Partager via


Setting a ToolTip on a TreeView control

A TreeView control in WinForms does not have a tooltip associated with and each node definately doesn't have a tooltip associated with it.  The way to get around this is to use the MouseMoved event and trigger the tooltip creation with this.

The MouseHover event prooved to be somewhat problematic in terms of figureing out where the point is to get at.  The useful method GetNodeAt is used on the tooltip to find the specific node I want to reference inside the treeview itself.

You need to keep track of the Active status of the tooltip, since it you set it as active multiple times it will wait for the 300 milliseconds again before displaying itself so it will never be displayed.

public class MainWindow : System.Windows.Forms.Form
{
    public MainWindow()
    {
        //
        // Required for Windows Form Designer support
        //
        InitializeComponent();
        // Initialize the tooltip
        toolTip1.InitialDelay = 300;
        toolTip1.ReshowDelay = 0;
    }
    private void TimeLineTreeView_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
    {
        TreeNode node = TimeLineTreeView.GetNodeAt(e.X, e.Y);
        if (node != null)
        {
            if (node.Tag != null && node.Tag is IIncidentEvent)
            {
                IIncidentEvent ev = (IIncidentEvent)node.Tag;
                if (!toolTip1.Active)
                {
                    toolTip1.SetToolTip(TimeLineTreeView, ev.ShortDescription);
                    toolTip1.Active = true;
                }
            }
            else
            {
                toolTip1.Active = false;
            }
        }
        else
        {
            toolTip1.Active = false;
        }
    }
}