Search code examples
c#tooltipownerdrawndrawstring

Text Alignment on OwnerDraw Tooltip in C# / .NET


I have a multiline text string (e.g. "Stuff\nMore Stuff\nYet More Stuff"), and I want to paint it, along with a bitmap into a tooltip. Since I am painting the bitmap, I need to set OwnerDraw to true, which I am doing. I am also handling the Popup event, so I can size the tooltip to be large enough to hold the text and the bitmap.

I am calling e.DrawBackground and e.DrawBorder(), and then painting my bitmap on the left side of the tooltip area.

Is there a set of flags I can pass to e.DrawText() in order to left-align the text, but to offset it so that it doesn't get painted over my bitmap? Or do I need to custom draw all the text as well (which will probably involve splitting the string on newlines, etc)?

UPDATED: The final code looks like this:

private void _ItemTip_Draw(object sender, DrawToolTipEventArgs e)
{
  e.DrawBackground();
  e.DrawBorder();

  // Reserve a square of size e.Bounds.Height x e.Bounds.Height
  // for the image. Keep a margin around it so that it looks good.
  int margin = 2;
  Image i = _ItemTip.Tag as Image;  
  if (i != null)
  {
    int side = e.Bounds.Height - 2 * margin;  
    e.Graphics.DrawImage(i, new Rectangle(margin, margin, side, side));
  }

  // Construct bounding rectangle for text (don't want to paint it over the image).
  int textOffset = e.Bounds.Height + 2 * margin; 
  RectangleF rText = e.Bounds;
  rText.Offset(textOffset, 0);
  rText.Width -= textOffset;

  e.Graphics.DrawString(e.ToolTipText, e.Font, Brushes.Black, rText);
}

Solution

  • I assume that if you define the bounding rectangle to draw in (calculating the image offset yourself) you could just:

         RectangleF rect = new RectangleF(100,100,100,100);
         e.Graphics.DrawString(myString, myFont, myBrush, rect);