Click here to Skip to main content
15,892,537 members
Articles / Programming Languages / C#
Article

ToolTipListBox - a list box with tool tips

Rate me:
Please Sign up or sign in to vote.
4.77/5 (16 votes)
31 Jul 20021 min read 184.3K   2.7K   50   23
A ListBox derived class that shows tool-tips for items that won't fit within the width of the list box

Introduction

I was working on a project where I needed to have a list-box that would show tool tips for items that will not fit within the width of the list-box. Initially I thought there would be a .NET BCL class that would have this facility. I've had forgettable experiences in the past where I'd waste my time writing something that was already available. But this time I found nothing that met my requirements. So I wrote my own list box class derived from the .NET System.Windows.Forms.ListBox class and called it ToolTipListBox.

What it does

Whenever an item in the ToolTipListBox list-box exceeds the width of the list-box control, a tool-tip is floated just over the item. Tool-tips are floated only for items that won't fit within the width of the list-box. For items that do fit in, the tool-tip will not be shown.

Using it

Simply declare your list-box objects as members of the ToolTipListBox class instead of the standard ListBox class. That's all. You'll also have to include the ToolTipListBox class source file in your project. Or you might even build a library and reference it instead.

Class source listing

C#
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Runtime.InteropServices;


public class ToolTipListBox : System.Windows.Forms.ListBox
{
    [StructLayout(LayoutKind.Sequential)]
    public struct SIZE
    {
        public int cx;
        public int cy;
    }
    [DllImport("gdi32.dll")]
    public static extern int GetTextExtentPoint32(IntPtr hdc, 
        String str, int len, ref SIZE size);

    [DllImport("user32.dll")]
    public static extern IntPtr GetDC(IntPtr hWnd);

    [DllImport("user32.dll")]
    public static extern int ReleaseDC(IntPtr hWnd,IntPtr hdc);


    public ToolTipListBox()
    {           
        tp.InitialDelay = 500;
        tp.ReshowDelay = 500;
        tp.AutoPopDelay = 3000;         
        tp.Active = true;           
    }   


    protected override void OnMouseMove(
        System.Windows.Forms.MouseEventArgs e)
    {               
        /* Get the index of the mouse-hovered item */
        int index = IndexFromPoint(e.X,e.Y);

        /* Ensure that there is an item */
        if(index != ListBox.NoMatches )
        {               
            /* 
              Check if the mouse has moved enough
              distance for a new index 
            */
            if( LastIndex != index )
            {
                string s = Items[index].ToString(); 

                /* Get the text extent */
                IntPtr hdc = GetDC(this.Handle);
                SIZE size;
                size.cx = 0;
                size.cy = 0;
                GetTextExtentPoint32(hdc,s,s.Length,ref size);
                ReleaseDC(this.Handle,hdc);

                /* If it won't fit show tool-tip */
                if(this.Width < size.cx)                    
                    tp.SetToolTip(this,s);

                LastIndex = index;              
            }                           
        }
    }

    private ToolTip tp = new ToolTip();
    private int LastIndex = -1;

}

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
United States United States
Nish Nishant is a technology enthusiast from Columbus, Ohio. He has over 20 years of software industry experience in various roles including Chief Technology Officer, Senior Solution Architect, Lead Software Architect, Principal Software Engineer, and Engineering/Architecture Team Leader. Nish is a 14-time recipient of the Microsoft Visual C++ MVP Award.

Nish authored C++/CLI in Action for Manning Publications in 2005, and co-authored Extending MFC Applications with the .NET Framework for Addison Wesley in 2003. In addition, he has over 140 published technology articles on CodeProject.com and another 250+ blog articles on his WordPress blog. Nish is experienced in technology leadership, solution architecture, software architecture, cloud development (AWS and Azure), REST services, software engineering best practices, CI/CD, mentoring, and directing all stages of software development.

Nish's Technology Blog : voidnish.wordpress.com

Comments and Discussions

 
GeneralReally helped me out! Pin
Andrew Blackburn23-Dec-08 3:16
Andrew Blackburn23-Dec-08 3:16 
GeneralMouse Click Over Tooltip Pin
Saied Javadi31-Aug-08 19:05
Saied Javadi31-Aug-08 19:05 
QuestionTooltips for Combobox items ...???? Pin
Srivatsa Haridas16-Jan-08 19:52
professionalSrivatsa Haridas16-Jan-08 19:52 
GeneralToolTip overlay [modified] Pin
ZooZee1-May-07 0:39
ZooZee1-May-07 0:39 
GeneralRe: ToolTip overlay Pin
Marco Rosas8-Aug-07 6:40
Marco Rosas8-Aug-07 6:40 
GeneralThank you Pin
rgeezy2-Nov-06 7:18
rgeezy2-Nov-06 7:18 
GeneralRe: Thank you Pin
wlin7102051722-Nov-06 3:29
wlin7102051722-Nov-06 3:29 
GeneralRe: Thank you Pin
wlin7102051722-Nov-06 3:42
wlin7102051722-Nov-06 3:42 
GeneralRe: Thank you Pin
Anil_Atta25-Apr-07 7:54
Anil_Atta25-Apr-07 7:54 
Questioncan this feature works in ASP??? Pin
rachellim9-Aug-06 17:00
rachellim9-Aug-06 17:00 
GeneralGreat code Pin
Scarsymmetry18-Jul-06 0:17
Scarsymmetry18-Jul-06 0:17 
QuestionThis is not Supported on Framework 1.0 Pin
TanmaySN29-Nov-05 0:24
TanmaySN29-Nov-05 0:24 
QuestionCan u do it For ASP.net Pin
.NET Follower5-May-05 23:42
.NET Follower5-May-05 23:42 
AnswerRe: Can u do it For ASP.net Pin
/randz5-Feb-07 19:31
/randz5-Feb-07 19:31 
QuestionNOT WORKING ??? Pin
De Nardis Andrea17-Feb-05 5:16
De Nardis Andrea17-Feb-05 5:16 
AnswerRe: NOT WORKING ??? Pin
De Nardis Andrea17-Feb-05 5:53
De Nardis Andrea17-Feb-05 5:53 
I think to have found the problem.
I send you a utility class that can fit your needs:
<br />
	/**<br />
	 * \brief Classe di calcolo della dimensione del testo<br />
	 * \date 16/02/05<br />
	 * <br />
	 * Questa classe contiene codice nativo<br />
	 * La classe consente di determinare il rettangolo in cui e'contenuto il testo<br />
	 * usando un device context del dispositivo stesso.<br />
	 */<br />
	public class textextent<br />
	{<br />
		private System.Windows.Forms.Form m_form;<br />
		private System.Windows.Forms.Control m_control;<br />
		private IntPtr m_wnd;<br />
		[StructLayout(LayoutKind.Sequential)]<br />
		public struct SIZE<br />
		{<br />
			public int cx;<br />
			public int cy;<br />
		}<br />
		[DllImport("gdi32.dll")]<br />
		private static extern int GetTextExtentPoint32(IntPtr hdc, <br />
			String str, int len, ref SIZE size);<br />
		[DllImport("gdi32.dll")]<br />
		private static extern System.IntPtr SelectObject (IntPtr hdc, IntPtr newobj);<br />
<br />
		[DllImport("user32.dll")]<br />
		private static extern IntPtr GetDC(IntPtr hWnd);<br />
<br />
		[DllImport("user32.dll")]<br />
		private static extern int ReleaseDC(IntPtr hWnd,IntPtr hdc);<br />
<br />
		/**<br />
		 * costruttore utile per le finetre<br />
		 * \param graphicObj oggetto grafico di tipo finestra<br />
		 */<br />
		public textextent(System.Windows.Forms.Form graphicObj)<br />
		{<br />
			m_wnd = graphicObj.Handle;<br />
			m_form = graphicObj;<br />
			if (m_form == null)<br />
				throw new ArgumentNullException ("graphicObj");<br />
		}<br />
		/**<br />
		 * costruttore utile per i controlli<br />
		 * \param graphicObj oggetto grafico di tipo controllo<br />
		 */<br />
		public textextent(System.Windows.Forms.Control graphicObj)<br />
		{<br />
			m_wnd = graphicObj.Handle;<br />
			m_control = graphicObj;<br />
			if (m_control == null)<br />
				throw new ArgumentNullException ("graphicObj");<br />
		}<br />
		/**<br />
		 * \brief Calcolo della dimensione del testo<br />
		 * \param str testo da controllare<br />
		 * \return struttura con la dimensione del testo<br />
		 */<br />
		public System.Drawing.Size getExtent (string str)<br />
		{<br />
			System.IntPtr fntpt;<br />
			if (m_control != null)<br />
			{<br />
				fntpt = m_control.Font.ToHfont ();<br />
			}<br />
			else<br />
			{<br />
				fntpt = m_form.Font.ToHfont ();<br />
			}<br />
			System.Diagnostics.Debug.Assert (0 != (long) fntpt);<br />
			if (0 == (long) fntpt)<br />
			{<br />
				throw new EntryPointNotFoundException ();<br />
			}<br />
			IntPtr hdc = GetDC(m_wnd);<br />
			System.IntPtr oldobj = SelectObject (hdc, fntpt);<br />
			SIZE size;<br />
			size.cx = 0;<br />
			size.cy = 0;<br />
			GetTextExtentPoint32(hdc, str, str.Length, ref size);<br />
			SelectObject (hdc, oldobj);<br />
			ReleaseDC(m_wnd,hdc);<br />
			System.Drawing.Size ret = new System.Drawing.Size (size.cx, size.cy);<br />
			return ret;<br />
		}<br />
	}<br />

Sorry,
comments are in Italian...
Please tell me if this is correct.
Regards,
AndreaLaugh | :laugh:
GeneralToolTip in a TreeView Control Pin
gsantanaz12-Jan-05 11:49
gsantanaz12-Jan-05 11:49 
GeneralToolTip on ComboBox Pin
Deena27-Nov-02 19:09
Deena27-Nov-02 19:09 
GeneralRe: ToolTip on ComboBox Pin
Filipczako25-Aug-05 12:44
Filipczako25-Aug-05 12:44 
GeneralNice :) Pin
leppie1-Aug-02 7:50
leppie1-Aug-02 7:50 
QuestionWhat would be nice... Pin
Shog91-Aug-02 2:10
sitebuilderShog91-Aug-02 2:10 
AnswerRe: What would be nice... Pin
Nish Nishant1-Aug-02 6:05
sitebuilderNish Nishant1-Aug-02 6:05 
GeneralRe: What would be nice... Pin
Shog91-Aug-02 6:10
sitebuilderShog91-Aug-02 6:10 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.