星期三, 九月 10, 2008

C# Tooltip ComboBox

Found some nice example from Zhixin Ye's post at msdn forum and updated it.

For better display result, need to hookup container form Move, MouseEnter events and call HideToolTip();

using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Windows.Forms;

///
/// Show tooltip for combobox
/// Parent needs to handle move/mouseenter event and call HideTooltip
///
class TooltipCombobox : ComboBox
{
ToolTip _tooltip = new ToolTip();
int _index = -1;
Point _point = new Point();

public TooltipCombobox()
{
DrawMode = DrawMode.OwnerDrawFixed;
DrawItem += new DrawItemEventHandler(TooltipCombobox_DrawItem);
LostFocus += new EventHandler(TooltipCombobox_LostFocus);
}

public void HideTooltip()
{
_tooltip.Hide(this);
}

void TooltipCombobox_LostFocus(object sender, EventArgs e)
{
HideTooltip();
}
void TooltipCombobox_DrawItem(object sender, DrawItemEventArgs e)
{
if (e.Index <>= Items.Count)
{
return;
}

string text = GetItemText(Items[e.Index]);

e.DrawBackground();

using (SolidBrush br = new SolidBrush(e.ForeColor))
{
e.Graphics.DrawString(text, e.Font, br, e.Bounds);
}

if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
{
SizeF sf = e.Graphics.MeasureString(text, this.Font);
if (sf.Width > this.Width)
{
int y = e.Bounds.Top - 1;
if ((e.State & DrawItemState.ComboBoxEdit) != DrawItemState.ComboBoxEdit)
{
y = e.Bounds.Bottom + 5;
}

_index = e.Index;
_point.X = e.Bounds.Left;
_point.Y = y;
_tooltip.Show(text, this, e.Bounds.Left, y);
}
else
{
HideTooltip();
}
}

e.DrawFocusRectangle();
}
}


没有评论:

发表评论