我正在为 Windows Mobile 应用程序创建从 ListView 继承的所有者绘制控件。我Graphics.DrawString
用来写出两行文本字符串(使用.NET CF 3.5)。问题是某些项目的文本特别长,不适合两行。谷歌搜索找到了使用MeasureString
和手动截断我的字符串的方法,但这仅适用于单行字符串。有什么办法可以在这里得到省略号,还是我必须接受剪切的文本或重新设计以仅使用一行?(两者都不是交易破坏者,但省略号肯定会很好。)
问问题
1343 次
1 回答
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;
}
于 2010-09-13T04:57:45.560 回答