110,538
社区成员
发帖
与我相关
我的任务
分享
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
listBox1.DrawMode = DrawMode.OwnerDrawFixed;//设置ListBox中每一项都手动绘制
listBox1.Items.Add("成功");
listBox1.Items.Add("失败");
listBox1.Items.Add("事业");
listBox1.Items.Add("成仁");
}
//绘制ListBox项的方法
private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
listBox1.DrawMode = DrawMode.OwnerDrawFixed;
e.DrawBackground();
Brush myBrush = Brushes.Black;
switch (listBox1.Items[e.Index].ToString())
{
case "成功":
myBrush = Brushes.Blue;
Console.WriteLine(listBox1.Items[e.Index].ToString());
break;
case "失败":
myBrush = Brushes.Red;
Console.WriteLine(listBox1.Items[e.Index].ToString());
break;
default:
myBrush = Brushes.Purple;
Console.WriteLine(listBox1.Items[e.Index].ToString());
break;
}
e.Graphics.DrawString(listBox1.Items[e.Index].ToString(), e.Font, myBrush, e.Bounds, StringFormat.GenericDefault);
e.DrawFocusRectangle();
}
}
private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
string StarText=listBox1.Items[e.Index].ToString();
string EndText = StarText.Remove(0, 3);
e.Graphics.DrawString(StarText.Substring(0, 3), e.Font, Brushes.Black, e.Bounds);
switch (EndText)
{
case "成功":
e.Graphics.DrawString(" " + StarText.Remove(0, 3), e.Font, Brushes.Red, e.Bounds);
break;
case "失败":
e.Graphics.DrawString(" " + StarText.Remove(0, 3), e.Font, Brushes.Blue, e.Bounds);
break;
default:
e.Graphics.DrawString(" " + StarText.Remove(0, 3), e.Font, Brushes.Black, e.Bounds);
break;
}
e.DrawFocusRectangle();
}
public struct KeyColor
{
public string key;
public Color color;
public KeyColor(string key, Color color)
{
this.key = key;
this.color = color;
}
}
private void Form1_Load(object sender, EventArgs e)
{
listBox1.Items.Add("第一次成功、第二次失败");
listBox1.Items.Add("第三次失败。");
listBox1.Items.Add("第四次未知");
}
private KeyColor[] keyColors = new KeyColor[] {
new KeyColor("成功", Color.Blue),
new KeyColor("失败", Color.Red),
new KeyColor("未知", Color.Green) };
private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
Brush brush = new SolidBrush(e.ForeColor);
string itemText = listBox1.Items[e.Index].ToString();
string backText = itemText;
foreach (KeyColor keyColor in keyColors)
backText = backText.Replace(keyColor.key, new string(' ', keyColor.key.Length));
if (string.Compare(itemText, backText) == 0)
e.Graphics.DrawString(itemText, e.Font, brush, e.Bounds, StringFormat.GenericDefault);
else
{
foreach (KeyColor keyColor in keyColors)
{
string markText = itemText.Replace(keyColor.key, new string(' ', keyColor.key.Length));
string foreText = string.Empty;
for (int i = 0; i < itemText.Length; i++)
foreText += markText[i] == ' ' ? itemText[i] : ' ';
e.Graphics.DrawString(foreText, e.Font,
new SolidBrush(keyColor.color), e.Bounds, StringFormat.GenericDefault);
}
e.Graphics.DrawString(backText, e.Font, brush, e.Bounds, StringFormat.GenericDefault);
}
e.DrawFocusRectangle();
}