在 C# 中更改 ComboBox 荧光笔的颜色

4 c# user-interface combobox

嘿。ComboBox 中的荧光笔有问题。最近我不得不将 ComboBox 中的某些项目灰化,我通过手动(以编程方式)在ComboBox 中绘制字符串来做到这一点。在DrawMode.NORMAL下的 .NET 组合框中,当您单击箭头时,荧光笔将自动出现,并且荧光笔的背景颜色默认为近蓝色。问题是当我们将鼠标移到一个项目上时,悬停项目的前景色变为白色,但是当我们手动绘制项目(DrawMode.OwnerDrawVariable)时,它不起作用。你能帮我解决这个问题吗??

这就是我使项目变灰的方式,

private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
{
    e.DrawBackground();
    int index = e.Index;
    CombinationEntry aFunction = comboBox1.Items[index] as CombinationEntry;  //CombinationEntry is a custom object to hold the gray info. Gray if not available and black if available
    if (aFunction.myIsAvailable)
    {
        e.Graphics.DrawString(aFunction.ToString(), new Font("Arial", 10, FontStyle.Regular, GraphicsUnit.Pixel), Brushes.Black, new Point(e.Bounds.X, e.Bounds.Y));
    }
    else
    {
        e.Graphics.DrawString(aFunction.ToString(), new Font("Arial", 10, FontStyle.Regular, GraphicsUnit.Pixel), Brushes.Gray, new Point(e.Bounds.X, e.Bounds.Y));
    }
}
Run Code Online (Sandbox Code Playgroud)

Eri*_*ger 5

默认情况下,组合框中的文本以两种颜色之一绘制:

SystemColors.WindowText
Run Code Online (Sandbox Code Playgroud)

对于非突出显示的项目,或

SystemColors.HighlightText
Run Code Online (Sandbox Code Playgroud)

对于突出显示的项目。

这些颜色不是固定的,但可以由用户配置(例如,通过控制面板)。在典型的 Windows 配色方案中,WindowText 为黑色,HighlightText 为白色,但如果重新配置了配色方案,则情况并非总是如此。

为了确保无论用户如何配置他们的系统都能获得正确的颜色,并为突出显示和非突出显示的文本获得适当的颜色,而不是将 Brushes.Black 用于非禁用文本,请使用类似:

e.State == DrawItemState.Selected ?
    SystemBrushes.HighlightText : SystemBrushes.WindowText
Run Code Online (Sandbox Code Playgroud)

这基本上是说,如果您正在绘制的项目(e.State)的状态是 Selected(突出显示),请使用 SystemColors.HighlightText,否则使用 SystemColors.WindowText。

您可能还想使用:

SystemBrushes.GrayText
Run Code Online (Sandbox Code Playgroud)

而不是 Brushes.Gray,再次以防用户使用非标准配色方案并且纯灰色看起来不正确。而且,您可能还应该使用:

comboBox1.Font
Run Code Online (Sandbox Code Playgroud)

而不是创建 Arial 字体,以确保该字体与为表单上的 ComboBox 定义的字体相匹配。(同样创建一个 Font 对象而不处理它会导致资源泄漏。)