views:

16

answers:

1

I'm creating an owner-drawn control inherited from ListView for a Windows Mobile application. I'm using Graphics.DrawString to write out a two-line text string (using .NET CF 3.5). Problem is some items have particularly long text that doesn't fit on the two lines. Googling has found methods for using MeasureString and to manually truncate my string, but this only works on a single-line string. Is there any way to get the ellipses here, or do I have to either accept clipped text or redesign to use only a single line? (Neither is a deal-breaker, but ellipses sure would be nice.)

A: 

Yes, you can get the ellipses to display, but you'll have to do some P/Invoking (what's new?):

public static void DrawText(Graphics gfx, string text, Font font, Color color, int x, int y, int width, int height)
{
 IntPtr hdcTemp = IntPtr.Zero;
 IntPtr oldFont = IntPtr.Zero;
 IntPtr currentFont = IntPtr.Zero;

 try
 {
  hdcTemp = gfx.GetHdc();
  if (hdcTemp != IntPtr.Zero)
  {
   currentFont = font.ToHfont();
   oldFont = NativeMethods.SelectObject(hdcTemp, currentFont);

   NativeMethods.RECT rect = new NativeMethods.RECT();
   rect.left = x;
   rect.top = y;
   rect.right = x + width;
   rect.bottom = y + height;

   int colorRef = color.R | (color.G << 8) | (color.B << 16);
   NativeMethods.SetTextColor(hdcTemp, colorRef);

   NativeMethods.DrawText(hdcTemp, text, text.Length, ref rect, NativeMethods.DT_END_ELLIPSIS | NativeMethods.DT_NOPREFIX);
  }
 }
 finally
 {
  if (oldFont != IntPtr.Zero)
  {
   NativeMethods.SelectObject(hdcTemp, oldFont);
  }

  if (hdcTemp != IntPtr.Zero)
  {
   gfx.ReleaseHdc(hdcTemp);
  }

  if (currentFont != IntPtr.Zero)
  {
   NativeMethods.DeleteObject(currentFont);
  }
 }
}

NativeMethods is a class that has all of my native calls. Including:

internal const int DT_END_ELLIPSIS = 32768;
internal const int DT_NOPREFIX = 2048;


[DllImport("coredll.dll", SetLastError = true)]
internal static extern int DrawText(IntPtr hDC, string Text, int nLen, ref RECT pRect, uint uFormat);

[DllImport("coredll.dll", SetLastError = true)]
internal static extern int SetTextColor(IntPtr hdc, int crColor);

[DllImport("coredll.dll", SetLastError = true)]
internal static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject);

[DllImport("coredll.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool DeleteObject(IntPtr hObject);

[StructLayout(LayoutKind.Sequential)]
internal struct RECT
{
 public int left;
 public int top;
 public int right;
 public int bottom;

}
Bryan
I was afraid P/Invoke would be involved. But great answer!
Michael Itzoe