c#中combox设置为DrawMode.OwnerDrawFixed,可以自定义高度,再加载DrawItemEventHandler事件就可以改变item的字体,否则会不显示

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);
         }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值