简体   繁体   English

前景列表框颜色

[英]Foreground listbox color

So I have this code to change the background selection colour of a listbox item to red in the default Winforms. 因此,我有这段代码将默认Winforms中的列表框项目的背景选择颜色更改为红色。

if (e.Index < 0) return;
            // if the item state is selected then change the back color 
            if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
                e = new DrawItemEventArgs(e.Graphics,
                                          e.Font,
                                          e.Bounds,
                                          e.Index,
                                          e.State ^ DrawItemState.Selected,
                                          e.ForeColor,
                                          Color.Red); // Choose the color

            // Draw the background of the ListBox control for each item.
            e.DrawBackground();
            // Draw the current item text
            e.Graphics.DrawString(studentsListBox.Items[e.Index].ToString(), e.Font, Brushes.Black, e.Bounds, StringFormat.GenericDefault);
            // If the ListBox has focus, draw a focus rectangle around the selected item.
            e.DrawFocusRectangle();

This works fine but I also want to change the font color for the selected item. 这工作正常,但我也想更改所选项目的字体颜色。 How do I do it? 我该怎么做?

if (e.Index < 0)
    return;

Brush foreBrush = Brushes.Black; // non-selected text color
if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
{
    foreBrush = Brushes.White; // selected text color
    e = new DrawItemEventArgs(e.Graphics,
                              e.Font,
                              e.Bounds,
                              e.Index,
                              e.State ^ DrawItemState.Selected,
                              e.ForeColor,
                              Color.Red); // Choose the color 
}

// Draw the background of the ListBox control for each item. 
e.DrawBackground();
// Draw the current item text
e.Graphics.DrawString((sender as ListBox).Items[e.Index].ToString(), e.Font, foreBrush, e.Bounds, StringFormat.GenericDefault);
// If the ListBox has focus, draw a focus rectangle around the selected item. 
e.DrawFocusRectangle(); 

您是否只能提供e.ForeColor以外的其他颜色?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM