Change the background color of Winform ListView headers

前端 未结 2 753
孤街浪徒
孤街浪徒 2021-01-17 11:18

How can you change the background color of the Headers of a ListView?

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-17 11:40

    I know this is a little late to the party but I still saw this post and this would have helped me. Here is a little abstracted application of the code david supplied

    using System.Windows.Forms;
    using System.Drawing;
    
    //List view header formatters
    public static void colorListViewHeader(ref ListView list, Color backColor, Color foreColor)
    {
        list.OwnerDraw = true;
        list.DrawColumnHeader += 
            new DrawListViewColumnHeaderEventHandler
            (
                (sender, e) => headerDraw(sender, e, backColor, foreColor)
            );
        list.DrawItem += new DrawListViewItemEventHandler(bodyDraw);
    }
    
    private static void headerDraw(object sender, DrawListViewColumnHeaderEventArgs e, Color backColor, Color foreColor)
    {
        using (SolidBrush backBrush = new SolidBrush(backColor))
        {
            e.Graphics.FillRectangle(backBrush, e.Bounds);
        }
    
        using (SolidBrush foreBrush = new SolidBrush(foreColor))
        {
            e.Graphics.DrawString(e.Header.Text, e.Font, foreBrush, e.Bounds);
        }
    }
    
    private static void bodyDraw(object sender, DrawListViewItemEventArgs e)
    {
        e.DrawDefault = true;
    }
    

    Then call this in your form constructor

    public Form()
    {
        InitializeComponent();
        *CLASS NAME*.colorListViewHeader(ref myListView, *SOME COLOR*, *SOME COLOR*);
    }
    

    Just replace the *CLASS NAME* with whatever class you put the first bit of code in and the *SOME COLOR*'s with some sort of color.

    //Some examples:
    Color.white
    SystemColors.ActiveCaption
    Color.FromArgb(0, 102, 255, 102);
    

提交回复
热议问题