C# 将鼠标悬停在组合框上时更改其背面颜色
我有一个组合框,我修改如下: 该颜色的代码是一个带有字符串的数组,如7FFFD4:C# 将鼠标悬停在组合框上时更改其背面颜色,c#,forms,combobox,C#,Forms,Combobox,我有一个组合框,我修改如下: 该颜色的代码是一个带有字符串的数组,如7FFFD4: private void cboCategory_DrawItem(object sender, DrawItemEventArgs e) { if (e.Index != -1) { e.DrawBackground(); e.Graphics.FillRectangle(new SolidBrush(ColorTranslator.FromHtml(cat_co
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();
}
}
我现在的目标是在将鼠标悬停在某个项目上时更改项目的背景颜色。这可能吗?我相信您试图在传统的Windows窗体应用程序中实现这一点。基于“悬停”修改颜色的示例位于鼠标事件中 鼠标进入 鼠标移动 鼠标悬停/鼠标向下/鼠标滚轮 鼠标移动 老鼠叶子 在我们的特定实例中,我们希望将重点放在悬停、下降和转轮事件上。可以找到一个有用的项目。允许您修改的示例如下:
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();
}
}
}
你可以找到深入的信息
但你可以锚定:
public void cmbContent_MouseHover(object sender, EventArgs e)
{
// Logic
}
这将为你做这项工作
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();
}
这里有一个例子,其中的项目文本是改变的,但它可能有助于你看起来很好。。。我马上就去试试。谢谢。我终于得到了我想要的颜色,但是当我关闭下拉列表时,颜色会保持不变,这是我不想要的。也许有一种方法可以在关闭下拉列表时更改背景颜色?你认为这就是你想要的吗。处理此事件以在关闭下拉列表时设置背景色。但是,如果我在该事件中写入:[combobox1.BackColor=color.Red;]则不会发生任何更改。我认为必须在cboCategory_DrawItem事件中编写一些代码才能显示。。。还是我错了?