原創噢。
重寫“重畫”方法,如果內容過長,則自動截取,只顯示一行能顯示下的內容。
protected override void OnPaint(PaintEventArgs e)
{
bool overMaxLength = false;
if (!canWordWrap)
{
SizeF thisSize = e.Graphics.MeasureString(this.Text, this.Font);
string text = this.Text;
while (thisSize.Width + e.Graphics.MeasureString("a", this.Font).Width >
this.Width + this.Margin.Left + this.Margin.Right)
{
text = text.Substring(0, text.Length – 1);
thisSize = e.Graphics.MeasureString(text, this.Font);
overMaxLength = true;
}
//if (overMaxLength)
//{
// this.realText = this.Text;
//}
//this.Text = text;
if (overMaxLength)
{
Rectangle face = new Rectangle();
face.X = 0;
face.Y = 0;
face.Width = this.Width;
face.Height = this.Height;
StringFormat sf = new StringFormat();
sf.Alignment = TranslateAlignment(this.TextAlign);
sf.LineAlignment = TranslateLineAlignment(this.TextAlign);
e.Graphics.DrawString(text, this.Font, new SolidBrush(this.ForeColor), face, sf);
}
}
else
{
this.realText = this.Text;
}
if (!overMaxLength)
{
base.OnPaint(e);
}
}