Pages

Sunday, April 15, 2012

RichToolTip in C#

I wanted to display some important test results on Datagrid cells. But the default cell tooltip displays only plain texts. A rich text box would allow me to format my results in a easy to read form highlight PASS/FAIL etc.

I found a couple of useful links:
  1. MFC based: RichText Tool-tip Control
  2. An awesome HTML tooltip A Professional HTML Renderer You Will Use
Then I came across this - How to print the content of a RichTextBox control by using Visual C# - a printable rich text box. I remembered that while investigating the C# ToolTip class methods earlier, I had figured out it could display images... voila!

Below is the tool tip implementation I came with using the printable rich text box control above:

public class RichToolTip : ToolTip
    {
        Size toolTipSize = new Size();

        /// 
        /// Gets or sets the RichTextBoxPrintCtrl to show as tool tip
        /// 
        public RichTextBoxPrintCtrl RtbPCtrl { get; set; }

        public RichToolTip()
        {
            OwnerDraw = true;
            Popup += new PopupEventHandler(RichToolTip_Popup);
            Draw += new DrawToolTipEventHandler(RichToolTip_Draw);
            RtbPCtrl = new RichTextBoxPrintCtrl();
        }

        void RichToolTip_Draw(object sender, DrawToolTipEventArgs e)
        {
            e.Graphics.Clear(Color.White);

            using (Image image = new Bitmap(toolTipSize.Width, toolTipSize.Height))
            {
                using (Graphics g = Graphics.FromImage(image))
                {
                    RtbPCtrl.Print(0, RtbPCtrl.Text.Length, g, new Rectangle(RtbPCtrl.Location, toolTipSize));
                }
                e.Graphics.DrawImageUnscaled(image, e.Bounds);
            }
        }

        //Fires before the draw event. So set the tooltip size here.
        void RichToolTip_Popup(object sender, PopupEventArgs e)
        {
            using (Graphics g = RtbPCtrl.CreateGraphics())
            {
                toolTipSize = g.MeasureString(RtbPCtrl.Rtf.Trim(), RtbPCtrl.Font).ToSize();                
                e.ToolTipSize = toolTipSize;
            }
        }
    }


No comments:

Post a Comment