Qos*_*smo 12 c# background listbox selection winforms
它似乎使用Windows设置中的默认颜色,默认为蓝色.假设我想将其永久更改为红色.我正在使用Winforms.
提前致谢.
RRU*_*RUZ 40
您必须覆盖该Drawitem
事件并将DrawMode
属性设置为DrawMode.OwnerDrawFixed
检查这个样本
private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
if (e.Index<0) return;
//if the item state is selected them 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.Yellow);//Choose the color
// Draw the background of the ListBox control for each item.
e.DrawBackground();
// Draw the current item text
e.Graphics.DrawString(listBox1.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();
}
Run Code Online (Sandbox Code Playgroud)
小智 6
希望这将有助于未来的人,因为上面的代码帮助了我,但不是100%
我仍然遇到以下问题:
- 当我选择另一个索引时,新选择的索引也会突出显示红色.
- 当我更改列表框的字体大小时,突出显示的区域将变小.
下面修复了这个问题
private void lstCartOutput_MeasureItem(object sender, MeasureItemEventArgs e)
{
// Cast the sender object back to ListBox type.
ListBox listBox = (ListBox)sender;
e.ItemHeight = listBox.Font.Height;
}
private void lstCartOutput_DrawItem(object sender, DrawItemEventArgs e)
{
ListBox listBox = (ListBox)sender;
e.DrawBackground();
Brush myBrush = Brushes.Black;
if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
{
myBrush = Brushes.Red;
e.Graphics.FillRectangle(new SolidBrush(Color.FromArgb(0, 64, 64)), e.Bounds);
}
else
{
e.Graphics.FillRectangle(Brushes.White, e.Bounds);
}
e.Graphics.DrawString(listBox.Items[e.Index].ToString(),e.Font, myBrush, e.Bounds);
e.DrawFocusRectangle();
}
Run Code Online (Sandbox Code Playgroud)
我也引用了MSDN网站.