日期:2014-05-18 浏览次数:21567 次
public class ComboBoxToolTip : ComboBox
{
private ToolTip itemToolTip;
/// <summary>
/// ComboBox 控件选择项带ToolTip提示的
/// 当 选择项 长度大于本身 ComboBox 控件时 生成ToolTip提示
/// </summary>
public ComboBoxToolTip()
{
this.DrawMode = DrawMode.OwnerDrawFixed;
this.DrawItem += new DrawItemEventHandler(DrawItemInList);
this.DropDownClosed += new EventHandler(DropDownListIsClosed);
this.itemToolTip = new ToolTip();
}
void DropDownListIsClosed(object sender, EventArgs e)
{
this.itemToolTip.Hide(this);
}
private bool IsTruncated(string text, Graphics graphics, Font font, Rectangle destinationBounds)
{
SizeF size = graphics.MeasureString(text, font);
Rectangle offsetToZeroRect = new Rectangle(0, 0, destinationBounds.Width, destinationBounds.Height);
return !offsetToZeroRect.Contains((int)size.Width, (int)size.Height);
}
void DrawItemInList(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
string text = this.Items[e.Index].ToString();
bool truncated;
using (Graphics graphics = e.Graphics)
{
graphics.DrawString(text, e.Font, Brushes.Black, e.Bounds, StringFormat.GenericDefault);
truncated = IsTruncated(text, graphics, e.Font, e.Bounds);
}
if ((e.State == DrawItemState.Selected) && (truncated))
{
this.itemToolTip.Show(text, this, e.Bounds.X + e.Bounds.Width, e.Bounds.Y + e.Bounds.Height);
}
else
{
this.itemToolTip.Hide(this);
}
e.DrawFocusRectangle();
}
}