c#中combox设置为DrawMode.OwnerDrawFixed,可以自定义高度,再加载DrawItemEventHandler事件就可以改变item的字体,否则会不显示
1.serial_cBox[num].DrawMode = DrawMode.OwnerDrawFixed;
serial_cBox[num].ItemHeight = port_Box_high - 6;//itme的高度和box高度之间的关系,从别的博客上看到
2.serial_cBox[num].DrawItem += new DrawItemEventHandler(this.ComboBox_DrawItem);
3.
ComboBox_DrawItem(object sender, DrawItemEventArgs e)
{
try
{
//匿名方法
Func<Color> SetBackColor = () =>
{
if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
{
return Color.Lime; //高亮背景色
}
return e.BackColor;
}
ComboBox cmb = sender as ComboBox; //当前的ComboBox控件
SolidBrush myBrush = new SolidBrush(cmb.ForeColor); //字体颜色
Font ft = cmb.Font; //获取在属性中设置的字体
//选项的文本
string itemText = cmb.GetItemText(cmb.Items[e.Index]);//cmb.Items[e.Index].ToString();
// 计算字符串尺寸(以像素为单位)
SizeF ss = e.Graphics.MeasureString(itemText, cmb.Font);
// 水平居中
float left = 0;
//left = (float)(e.Bounds.Width - ss.Width) / 2; //如果需要水平居中取消注释
if (left < 0) left = 0f;
// 垂直居中
float top = (float)(e.Bounds.Height - ss.Height) / 2;
if (top <= 0) top = 0f;
// 输出
e.DrawBackground();
//选项背景高亮
Rectangle rectangle1 = new Rectangle(e.Bounds.Left, e.Bounds.Top,
e.Bounds.Width, e.Bounds.Height);
e.Graphics.FillRectangle(new SolidBrush(SetBackColor()), rectangle1);
//填充选项背景
int x = 0, y = 0;
Rectangle rectangle = new Rectangle(e.Bounds.Left + x, e.Bounds.Top + y,
e.Bounds.Width - 2 * x, e.Bounds.Height - 2 * y);
e.Graphics.FillRectangle(new SolidBrush(Color.FromArgb(255, ColorTranslator.FromHtml("#ffffff"))), rectangle);
e.Graphics.DrawString(itemText, ft, myBrush, new RectangleF(
e.Bounds.X + left, //设置X坐标偏移量
e.Bounds.Y + top, //设置Y坐标偏移量
e.Bounds.Width, e.Bounds.Height), StringFormat.GenericDefault);
//e.Graphics.DrawString(cmb.GetItemText(cmb.Items[e.Index]), ft, myBrush, e.Bounds, StringFormat.GenericDefault);
e.DrawFocusRectangle();
}
catch (Exception ex)
{
//log.ErrorFormat("FrmAccountActivate窗体:" + ex.Message, ex);
}
}