【发布时间】:2010-06-12 03:37:24
【问题描述】:
我有自定义的面板。我用它来显示文本。但有时该文本太长并换行到下一行。有什么方法可以自动调整面板大小以显示所有文本?
我正在使用 C# 和 Visual Studio 2008 以及紧凑型框架。
这是我要调整大小的代码:
(注意:HintBox 是我自己的类,继承自面板。因此我可以根据需要对其进行修改。)
public void DataItemClicked(ShipmentData shipmentData)
{
// Setup the HintBox
if (_dataItemHintBox == null)
_dataItemHintBox = HintBox.GetHintBox(ShipmentForm.AsAnObjectThatCanOwn(),
_dataShipSelectedPoint,
new Size(135, 50), shipmentData.LongDesc,
Color.LightSteelBlue);
_dataItemHintBox.Location = new Point(_dataShipSelectedPoint.X - 100,
_dataShipSelectedPoint.Y - 50);
_dataItemHintBox.MessageText = shipmentData.LongDesc;
// It would be nice to set the size right here
_dataItemHintBox.Size = _dataItemHintBox.MethodToResizeTheHeightToShowTheWholeString()
_dataItemHintBox.Show();
}
我将向 Will Marcouiller 给出答案,因为他的代码示例最接近我的需要(并且看起来可以工作)。但是,这是我认为我会使用的:
public static class CFMeasureString
{
private struct Rect
{
public readonly int Left, Top, Right, Bottom;
public Rect(Rectangle r)
{
this.Left = r.Left;
this.Top = r.Top;
this.Bottom = r.Bottom;
this.Right = r.Right;
}
}
[DllImport("coredll.dll")]
static extern int DrawText(IntPtr hdc, string lpStr, int nCount,
ref Rect lpRect, int wFormat);
private const int DT_CALCRECT = 0x00000400;
private const int DT_WORDBREAK = 0x00000010;
private const int DT_EDITCONTROL = 0x00002000;
static public Size MeasureString(this Graphics gr, string text, Rectangle rect,
bool textboxControl)
{
Rect bounds = new Rect(rect);
IntPtr hdc = gr.GetHdc();
int flags = DT_CALCRECT | DT_WORDBREAK;
if (textboxControl) flags |= DT_EDITCONTROL;
DrawText(hdc, text, text.Length, ref bounds, flags);
gr.ReleaseHdc(hdc);
return new Size(bounds.Right - bounds.Left, bounds.Bottom - bounds.Top +
(textboxControl ? 6 : 0));
}
}
这使用操作系统级别的调用来绘制文本。通过 P-Invoking 它,我可以获得我需要的功能(多行换行)。请注意,此方法不包括任何边距。只是文本占用的实际空间。
这段代码不是我写的。我是从http://www.mobilepractices.com/2007/12/multi-line-graphicsmeasurestring.html 那里得到的。那篇博客文章有我的确切问题和这个修复。 (虽然我确实做了一些小调整以使其成为扩展方法。)
【问题讨论】:
-
+1 因为 Compact Framework 问题可能会带来与完整框架本身不同的解决方案。
标签: c# visual-studio-2008 compact-framework