ToolTip with Images

1. December 2006 06:30 by Mrojas in General  //  Tags:   //   Comments (0)

The Tooltips that comes out of the box for winforms do not support images on them. This is a simple class that allows you to add Images and Text to your ToolTips

using System;

using System.Windows.Forms;

using System.Collections.Generic;

using System.Text;

using System.Drawing;

namespace CustomControls

{

class ToolTipWithImage : Control

{

private Image _img;

private Control _ctl;

private Timer _timer;

string _imgfilename;

string _tiptext;

public String TipText

{

get { return _tiptext; }

set { _tiptext = value; }

}

public String ImageFile

{

get

{

return _imgfilename;

}

set

{

if (_imgfilename == value)

{

}

else

{

_imgfilename = value;

try

{

_img = Image.FromFile(_imgfilename);

this.Size = new Size(_img.Width + 70, _img.Height);

}

catch

{

_img = null;

}

}

}

}

public ToolTipWithImage()

{

this.Location = new Point(0, 0);

this.Visible = false;

_timer = new Timer();

_timer.Interval = 1000;

_timer.Tick += new EventHandler(ShowTipOff);

}

public void SetToolTip(Control ctl)

{

_ctl = ctl;

ctl.Parent.Controls.Add(this);

ctl.Parent.Controls.SetChildIndex(this, 0);

ctl.MouseMove += new MouseEventHandler(ShowTipOn);

}

protected override void OnPaint(PaintEventArgs e)

{

if (_img != null)

{

e.Graphics.DrawImage(_img, 0, 0);

e.Graphics.DrawString(TipText, this.Font, Brushes.Black, _img.Width, 0);

}

}

public void ShowTipOn(object sender, MouseEventArgs e)

{

if (!this.Visible)

{

_timer.Start();

this.Left = _ctl.Left + e.X + 100;

this.Top = _ctl.Top + e.Y;

this.Visible = true;

}

}

public void ShowTipOff(Object sender, EventArgs e)

{

_timer.Stop();

this.Visible = false;

}

}

 

}

 

To use it just do something like

ToolTipWithImage timg = new ToolTipWithImage();

timg.TipText = "Hello";

timg.ImageFile = @"C:\Hello.gif";

timg.SetToolTip(btnOk);