Compact Framework:绘制带椭圆的多行字符串

时间:2010-09-09 16:16:24

标签: windows-mobile compact-framework drawstring

我正在为Windows Mobile应用程序创建一个从ListView继承的所有者绘制控件。我正在使用Graphics.DrawString写出一个双行文本字符串(使用.NET CF 3.5)。问题是某些项目具有特别长的文本,不适合两行。谷歌搜索已找到使用MeasureString和手动截断我的字符串的方法,但这只适用于单行字符串。有没有办法在这里获取省略号,或者我是否必须接受剪辑文本或重新设计才能使用一行? (也不是一个交易破坏者,但椭圆肯定会很好。)

1 个答案:

答案 0 :(得分:2)

是的,您可以显示省略号,但是你必须做一些P / Invoking(什么是新的?):

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是一个包含所有本机调用的类。包括:

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;

}