将鼠标悬停在其上时,更改组合框项目的颜色

时间:2014-11-07 18:53:45

标签: c# forms combobox

我有一个我这样修改过的ComboBox:

enter image description here

这个代码就是这个(cat_color是一个包含“#7FFFD4”等字符串的数组):

private void cboCategory_DrawItem(object sender, DrawItemEventArgs e)
{
    if (e.Index != -1)
    {
        e.DrawBackground();
        e.Graphics.FillRectangle(new SolidBrush(ColorTranslator.FromHtml(cat_color1[e.Index])), e.Bounds);
        Font f = cboCategory.Font;
        e.Graphics.DrawString(cboCategory.Items[e.Index].ToString(), f, new SolidBrush(ColorTranslator.FromHtml(cat_color2[e.Index])), e.Bounds, StringFormat.GenericDefault);
        e.DrawFocusRectangle();
    }
}

我现在的目标是当我将鼠标悬停在某个项目上时更改该项目的颜色。这可能吗?

2 个答案:

答案 0 :(得分:3)

这将为你完成这项工作。

if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
{
    e.DrawBackground();
    e.Graphics.FillRectangle(new SolidBrush(SystemColors.Highlight), e.Bounds);
    Font f = cboCategory.Font;
    e.Graphics.DrawString(cboCategory.Items[e.Index].ToString(), f, new SolidBrush(ColorTranslator.FromHtml(cat_color2[e.Index])), e.Bounds, StringFormat.GenericDefault);
    e.DrawFocusRectangle();
}

答案 1 :(得分:1)

我相信您尝试在传统的 Windows窗体应用程序中执行此操作。根据“悬停”修改颜色的示例将位于鼠标事件中。

  • 鼠标输入
  • 鼠标移动
  • 鼠标悬停/鼠标按下/鼠标滚轮
  • 鼠标向上
  • 鼠标离开

在我们的特定实例中,我们希望专注于 Hover,Down和Wheel Event 。可以找到一个有用的项目here。应该允许您修改的示例是:

 public class ComboTheme : ComboBox
    {
         new public DrawMode DrawMode { get; set; }
         public Color HighlightColor { get; set; }



    public ComboTheme()
     {
          base.DrawMode = DrawMode.OwnerDrawFixed;
          this.HighlightColor = Color.Red;
          this.DrawItem += new DrawItemEventHandler(ComboTheme_DrawItem); 
     }

     public void ComboTheme_DrawItem(object sender, DrawItemEventArgs e)
     {
          if(e.Index > 0)
          {
               ComboBox box = ((ComboBox)sender);
               if((e.State & DrawItemState.Selected) == DrawItemState.Selected)
               {
                    e.Graphics.FillRectangle(new SolidBrush(HighlightColor), e.Bounds);
               }

               else { e.Graphics.FillRectangle(new SolidBrush(box.BackColor), e.Bounds); }

               e.Graphics.DrawString(box.Items[e.Index].ToString(), 
                    e.Font, new SolidBrush(box.ForeColor),
                    new Point(e.Bounds.X, e.Bounds.Y));
               e.DrawFocusRectangle();
          }
     }

}

您可以深入了解here

但你可以锚定:

public void cmbContent_MouseHover(object sender, EventArgs e)
{
    // Logic
}