改变Listbox中的字体颜色

时间:2021-01-23 19:39:50
 
                                        改变Listbox中的字体颜色
        当用ListBox来作输出显示的时候,有时需要针对不同的输出显示不同的颜色,比如当用ListBox来作告警输出的时候,需要根据不同的告警等级来显示不同的颜色,以达到醒目的作用,其实用ListBox来做这种事情很容易。
        首先把ListBox的DrawMode设为OwnerDrawFixed或是OwnerDrawVariable,然后在ListBox的DrawItem事件中加入下面的代码
        private void listBox_DrawItem(object sender, DrawItemEventArgs e)
        {
            Brush FontBrush = null;
            ListBox listBox = sender as ListBox;
            if (e.Index > -1)
            {
                switch (listBox.Items[e.Index].ToString())
                {
                    case "Critical": FontBrush = Brushes.Brown; break;
                    case "Major": FontBrush = Brushes.Red; break;
                    case "Minor": FontBrush = Brushes.Orange; break;
                    case "Warning": FontBrush = Brushes.Yellow; break;
                    default: FontBrush = Brushes.Black; break;
                }
                e.DrawBackground();
                e.Graphics.DrawString(listBox.Items[e.Index].ToString(), e.Font, FontBrush, e.Bounds);
                e.DrawFocusRectangle();
            }
        }
即可。
完整的程序代码如下:以下代码在vs2005中测试通过
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
 
namespace ListBoxDataGrid
{
    public partial class ListBoxForm : Form
    {
        public ListBoxForm()
        {
            InitializeComponent();
        }
        private void listBox_DrawItem(object sender, DrawItemEventArgs e)
        {
            Brush FontBrush = null;
            ListBox listBox = sender as ListBox;
            if (e.Index > -1)
            {
                switch (listBox.Items[e.Index].ToString())
                {
                    case "Critical": FontBrush = Brushes.Brown; break;
                    case "Major": FontBrush = Brushes.Red; break;
                    case "Minor": FontBrush = Brushes.Orange; break;
                    case "Warning": FontBrush = Brushes.Yellow; break;
                    default: FontBrush = Brushes.Black; break;
                }
                e.DrawBackground();
                e.Graphics.DrawString(listBox.Items[e.Index].ToString(), e.Font, FontBrush, e.Bounds);
                e.DrawFocusRectangle();
            }
        }
        private void button_Click(object sender, EventArgs e)
        {
            if (!textBox.Text.Length.Equals(0))
                listBox.Items.Add(textBox.Text);
        }
    }
}
效果图如下:
改变Listbox中的字体颜色