C # override the OnDrawSubItem function of Listview to implement the progress bar.

Source: Internet
Author: User

I have always wanted to write a Listview component with a progress bar for future use. Because I am busy at work and have no time, I don't want to change my work time, so I am too lazy to write. It took some time to write it out when I was not busy at work.

Note: To re-paint the Listview subitem, you must set the value of the Listview OwnerDraw attribute to True, otherwise your rewriting will not take effect.

Component code:


 
 

Using System; using System. collections. generic; using System. componentModel; using System. diagnostics; using System. linq; using System. text; using System. windows. forms; using System. drawing; namespace Control. listview {partial class ProgressListview {// <summary> // Required designer variable. /// </summary> private System. componentModel. IContainer components = null; // <summary> // Clean up Any resources being used. /// </summary> /// <param name = "disposing"> true if managed resources shocould be disposed; otherwise, false. </param> protected override void Dispose (bool disposing) {if (disposing & (components! = Null) {components. dispose ();} base. dispose (disposing );} # region Component Designer generated code // <summary> // Required method for Designer support-do not modify // the contents of this method with the code editor. /// </summary> private void InitializeComponent () {components = new System. componentModel. container () ;}# endregion} public partial class ProgressListview: ListView {// /<Summary> // progress bar column index /// </summary> private int _ progressColumnIndex =-1; public int ProgressColumnIndex {get {return _ progressColumnIndex ;} set {_ progressColumnIndex = value ;}/// <summary> /// maximum progress bar /// </summary> private int _ progressMaximun = 100; public int ProgressMaximun {get {return _ progressMaximun;} public ProgressListview () {InitializeComponent ();} public ProgressListv Iew (IContainer container) {container. add (this); InitializeComponent ();} protected override void OnDrawColumnHeader (DrawListViewColumnHeaderEventArgs e) {e. drawDefault = true; base. onDrawColumnHeader (e);} protected override void OnDrawSubItem (DrawListViewSubItemEventArgs e) {if (e. columnIndex = ProgressColumnIndex) {var item = e. item. subItems [1]; var rect = item. bounds; // draw the progress bar var g = e. gra Phics; var progressRect = new Rectangle (rect. X + 1, rect. Y + 3, rect. width-2, rect. height-5); g. drawRectangle (new Pen (new SolidBrush (Color. blue), 1), progressRect); // draw the progress var progressMaxWidth = progressRect. width-1; var unit = (progressMaxWidth * 1.0)/(_ progressMaximun * 100); var fValue = float. parse (item. text); var percent = fValue * unit * 100; if (percent> = progressMaxWidth) percent = ProgressMaxWidth; g. fillRectangle (new SolidBrush (Color. red), new RectangleF (progressRect. X + 1, progressRect. Y + 1, float. parse (percent. toString (), progressRect. height-1); // percentage of painting progress percent = fValue; var percentText = string. format ("{0} %... ", percent); if (fValue> = _ progressMaximun) percentText =" completed "; var size = TextRenderer. measureText (percentText. toString (), Font); var x = rect. X + (pr OgressRect. width-size. width)/2.0; var y = rect. Y + (progressRect. height-size. height)/2.0 + 3; g. drawString (percentText, this. font, new SolidBrush (Color. black), float. parse (x. toString (), float. parse (y. toString ();} else {e. drawDefault = true;} base. onDrawSubItem (e);} public void SetProgress (int itemIndex, int value) {var columnWidth = this. columns [ProgressColumnIndex]. width; var prog RessSubItem = this. items [itemIndex]. subItems [ProgressColumnIndex]; progressSubItem. text = value. toString () ;}} using System; using System. collections. generic; using System. componentModel; using System. diagnostics; using System. linq; using System. text; using System. windows. forms; using System. drawing; namespace Control. listview {partial class ProgressListview {// <summary> // Required designer variab Le. /// </summary> private System. componentModel. IContainer components = null; // <summary> // Clean up any resources being used. /// </summary> /// <param name = "disposing"> true if managed resources shocould be disposed; otherwise, false. </param> protected override void Dispose (bool disposing) {if (disposing & (components! = Null) {components. dispose ();} base. dispose (disposing );} # region Component Designer generated code // <summary> // Required method for Designer support-do not modify // the contents of this method with the code editor. /// </summary> private void InitializeComponent () {components = new System. componentModel. container () ;}# endregion} public partial class ProgressListview: listView {// <summary> // progress bar column index /// </summary> private int _ progressColumnIndex =-1; public int ProgressColumnIndex {get {return _ progressColumnIndex ;} set {_ progressColumnIndex = value ;}/// <summary> /// maximum progress bar /// </summary> private int _ progressMaximun = 100; public int ProgressMaximun {get {return _ progressMaximun;} public ProgressListview () {InitializeComponent ();} public ProgressListview (IContainer container) {container. add (this); InitializeComponent ();} protected override void OnDrawColumnHeader (DrawListViewColumnHeaderEventArgs e) {e. drawDefault = true; base. onDrawColumnHeader (e);} protected override void OnDrawSubItem (DrawListViewSubItemEventArgs e) {if (e. columnIndex = ProgressColumnIndex) {var item = e. item. subItems [1]; var rect = item. bounds; // draw the progress bar var g = e. graphics; var progressRect = new Rectangle (rect. X + 1, rect. Y + 3, rect. width-2, rect. height-5); g. drawRectangle (new Pen (new SolidBrush (Color. blue), 1), progressRect); // draw the progress var progressMaxWidth = progressRect. width-1; var unit = (progressMaxWidth * 1.0)/(_ progressMaximun * 100); var fValue = float. parse (item. text); var percent = fValue * unit * 100; if (percent> = progressMaxWidth) percent = progressMaxWidth; g. fillRectangle (new SolidBrush (Color. red), new RectangleF (progressRect. X + 1, progressRect. Y + 1, float. parse (percent. toString (), progressRect. height-1); // percentage of painting progress percent = fValue; var percentText = string. format ("{0} %... ", percent); if (fValue> = _ progressMaximun) percentText =" completed "; var size = TextRenderer. measureText (percentText. toString (), Font); var x = rect. X + (progressRect. width-size. width)/2.0; var y = rect. Y + (progressRect. height-size. height)/2.0 + 3; g. drawString (percentText, this. font, new SolidBrush (Color. black), float. parse (x. toString (), float. parse (y. toString ();} else {e. drawDefault = true;} base. onDrawSubItem (e);} public void SetProgress (int itemIndex, int value) {var columnWidth = this. columns [ProgressColumnIndex]. width; var progressSubItem = this. items [itemIndex]. subItems [ProgressColumnIndex]; progressSubItem. text = value. toString ();}}}

The above is all the code of the ProgressListview component. The two methods of Listview are overwritten. The core code is in the OnDrawSubItem method, by drawing a rectangle with a border and a solid rectangle, you can achieve a simple progress bar. The OnDrawColumnHeader function is rewritten to set its DrawDefault to True, when the Ownerdraw attribute of Listview is set to True, OnDrawColumnHeader also requires re-painting by default. Here we do not need to re-paint the column header, so set its DrawDefault to true.

You can use the ProgressColumnIndex attribute to set the progress bar. You can also call the SetProgress function of the component to dynamically set the progress bar. The Maximun value of the progress bar is set to 100;

 


The following is the call code for this component:


 
 

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Threading;  namespace Control.Listview {     public partial class Form1 : Form     {         public Form1()         {             InitializeComponent();              CheckForIllegalCrossThreadCalls = false;             uploadListview1.ProgressColumnIndex = 1;             var percentArray = new int[] { 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };             foreach (var percent in percentArray)             {                 var listViewItem = new ListViewItem();                 uploadListview1.Items.Add(listViewItem);                 listViewItem.SubItems.AddRange(new string[] { percent.ToString(), (percent + 1).ToString(), (percent + 2).ToString() });             }         }          private void button1_Click(object sender, EventArgs e)         {             var th = new Thread(delegate()             {                 for (var i = 0; i < 101; i++)                 {                     uploadListview1.SetProgress(1, i);                     Thread.Sleep(100);                 }             });             th.IsBackground = true;             th.Start();         }       } } using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.Threading;namespace Control.Listview{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();            CheckForIllegalCrossThreadCalls = false;            uploadListview1.ProgressColumnIndex = 1;            var percentArray = new int[] { 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };            foreach (var percent in percentArray)            {                var listViewItem = new ListViewItem();                uploadListview1.Items.Add(listViewItem);                listViewItem.SubItems.AddRange(new string[] { percent.ToString(), (percent + 1).ToString(), (percent + 2).ToString() });            }        }        private void button1_Click(object sender, EventArgs e)        {            var th = new Thread(delegate()            {                for (var i = 0; i < 101; i++)                {                    uploadListview1.SetProgress(1, i);                    Thread.Sleep(100);                }            });            th.IsBackground = true;            th.Start();        }    }}


The constructor initializes ProgressListview. In this example, a progress bar is updated by clicking the button button1. When you click the button button1, the progress bar is updated, the percentage progress is displayed.

As shown in the following figure, the interface may not be very nice, haha.

 

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.