WinForm Customizing the listbox display style

Source: Internet
Author: User

WinForm Custom ListBox display style, multi-column different color display, effects such as:




First, drag a ListBox control to the WinForm window, named Lstconsole, and set DrawMode to: OwnerDrawFixed, it's important to note that otherwise our next job won't work.


Then we come from the definition ListBoxItem, the code is as follows:


    public class Coloredlistboxitem {//<summary>//Creates a new Coloredlistboxitem// </summary>//<param name= "prefix" >the prefix which would be used</param>//<param N Ame= "text" >the real message</param>//<param name= "color" >the color of both</param> p            Ublic Coloredlistboxitem (DateTime time, string prefix, string text, color color) {time = time;            Text = text;            Prefix = Prefix;        TextColor = color; }//<summary>//The real message///</summary> public DateTime time {get; SE T }//<summary>//The prefix of the text////</summary> public string Prefix {g Et Set  }///<summary>//The real message////</summary> public string Text {get; set; }///<summary>//The color of The message///</summary> public Color textcolor {get; set;} } public enum LogType {//<summary>//OpenVPN changed the internal STATE.L//</s        Ummary> Created,///<summary>//The management interface wants to say something. </summary> Changed,///<summary>/A "normal" message is logged by OpenVPN via Mans        Agement Interface. </summary> Deleted,///<summary>/A Debug message is sent.        This is the primary for internal usage. </summary> Renamed}


Next, switch to the event and add the DrawItem event to Lstconsole: Lstconsole_drawitem, the code is as follows:


private void Lstconsole_drawitem (object sender, DrawItemEventArgs e) {//Just in case the list is empty            ... if (E.index = =-1) return;            Prefixes is drawed bold font prefixfont = new Font (E.font, fontstyle.bold); Coloredlistboxitem li = (coloredlistboxitem) ((ListBox) sender).            Items[e.index]; Brush br = new SolidBrush (li.            TextColor); Calculate the width of the longest time int timewidth = (int) e.graphics.measurestring ("" + New DateTime (222 2, A, 222, CultureInfo.CurrentCulture.Calendar, datetimekind.local). ToString (), Prefixfont, E.bounds.width, Stringformat.genericdefault).            Width; Calculate the width of the longest prefix int prefixwidth = (int) e.graphics.measurestring ("[Management]", p Refixfont, E.bounds.width, Stringformat.genericdefault).            Width;            Prepare the prefix string prefix = ""; Switch (li. PrEfix) {case "Created": prefix = "[Create file]";                Break                    Case "Changed": prefix = "[modify file]";                Break                    Case "Deleted": prefix = "[delete file]";                Break                    Case "Renamed": prefix = "[rename file]";                Break            Default:break;            } e.drawbackground ();            Rectangle newbounds = new Rectangle (e.bounds.location, e.bounds.size); Draw the time e.graphics.drawstring (li.            Time.tostring (), Prefixfont, BR, Newbounds, Stringformat.genericdefault);            Calculate the new rectangle newbounds.x + = Timewidth;            Newbounds.width-= Timewidth;            Draw the prefix e.graphics.drawstring (prefix, Prefixfont, BR, Newbounds, Stringformat.genericdefault); Calculate the new RECtangle newbounds.x + = Prefixwidth;            Newbounds.width-= Prefixwidth; Draw the text e.graphics.drawstring (li.            Text, E.font, BR, Newbounds.x, Newbounds.y, Stringformat.genericdefault);        Draw the focus e.drawfocusrectangle (); }


In the final step, add the data that the item displays to the listbox:


        public void Addlog (LogType prefix, string text) {if (lstconsole.invokerequired) { try {//lstconsole.begininvoke (new Utilshelper.action<logtype, String&gt                ;(addlog), prefix, text);            } catch (ObjectDisposedException) {} return;            } Color Rowcolor;                    Switch (prefix) {case LogType.Created:rowColor = Color.green;                Break                    Case LogType.Changed:rowColor = Color.darkblue;                Break                    Case LogType.Deleted:rowColor = Color.brown;                Break                    Default://e.g. state Rowcolor = Color.Black;            Break            } lstconsole.beginupdate ();     if (LstConsole.Items.Count = = 2048)           LstConsole.Items.RemoveAt (0); LSTCONSOLE.ITEMS.ADD (New Coloredlistboxitem (DateTime.Now, prefix.            ToString (), text, Rowcolor));            int h = lstconsole.clientsize.height-lstconsole.margin.vertical;            int i = lstconsole.items.count-1;                while (H >= 0 && i > 0) {int nh = lstconsole.getitemheight (i);                if (nh > H) break;                    else {h-= NH;                i--;            }} lstconsole.topindex = i;        Lstconsole.endupdate (); }


Show effect software: Download windows file Monitor


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

WinForm Customizing the listbox display style

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.