[WinForm Detailed Tutorial 4] ProgressBar, ImageList and ListView controls in WinForm

1.ProgressBar

Used to display the progress of an operation.

Attributes:

  • Value: Represents the value of the current progress bar, its range is determined by Min and Max.
  • Step: Set the step size to increase each time the PerformStep() method is called.
  • MarqueeAnimationSpeed: When Style is set to Marquee, controls the scrolling speed in milliseconds.
  • Max: Set the maximum value of the progress bar.
  • Min: Set the minimum value of the progress bar.
  • Style: Set the style of the progress bar, including Blocks, Continuous and Marquee.

method:

  • PerformStep(): causes the progress bar to increase by the step set by the Step property.
  • Increment(int value): Increase the progress bar by the specified value.

Code example:

image-20231030162856183

namespace WinFormsTest
{
    public partial class frmProgressBar : Form
    {
        public frmProgressBar()
        {
            InitializeComponent();
        }

        private void frmProgressBar_Load(object sender, EventArgs e)
        {
            //pbrData.MarqueeAnimationSpeed = 0;//滚动的速度
            //pbrData.Style = ProgressBarStyle.Marquee;
            pbrData.Style = ProgressBarStyle.Continuous;
            pbrData.Maximum = 100;
            pbrData.Minimum = 0;
            pbrData.Value = 0;
            pbrData.Step = 1;
        }
        double count = 0;
        private void btnLoad_Click(object sender, EventArgs e)
        {
            //pbrData.MarqueeAnimationSpeed = 1000;//滚动的速度
            pbrData.Maximum = string.IsNullOrWhiteSpace(textBox1.Text) ? 100 : Convert.ToInt16(textBox1.Text);
            label1.Visible = true;
            timer1.Interval = 1000;//计时器每秒执行一次
            timer1.Enabled = true;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            // 当进度条的值达到最大值时,停止定时器
            if (pbrData.Value >= pbrData.Maximum)
            {
                timer1.Enabled = false;
                MessageBox.Show("加载完毕!");
            }
            else
            {
                count += pbrData.Step;
                pbrData.PerformStep();  // 进度条增加一个步长
                label1.Text = Convert.ToString(Convert.ToInt32((count / pbrData.Maximum) * 100)) + "%";
            }
        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            // 判断输入的字符是否为数字或控制字符(如退格键)
            if (!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar))
            {
                e.Handled = true; // 设置Handled为true,表示事件已处理,不再继续处理该字符的输入
            }
        }

        private void btnPause_Click(object sender, EventArgs e)
        {
            timer1.Enabled = false;
        }

        private void btnContinue_Click(object sender, EventArgs e)
        {
            timer1.Enabled = true;
        }
    }
}

Effect demonstration:

Animation 22

2. ImageList

ImageListUsed to store image resources and display them in associated controls. It is equivalent to a collection of pictures in itself.

Attributes

  • Images: Stores a collection of images. Each image has an index and optional key name in the collection.
  • ImageSize: The size of the image, ensuring that all images in the collection are displayed at the same size.
  • Name:ImageList The name of the control.

method

  • Add(Image/Icon): Add an image or icon to the Images collection.
  • Add(string, Image/Icon): Add an image or icon to the Images collection and specify a key name.
  • Contains(Image/String): Determine whether the Images collection contains the specified picture or key name.
  • IndexOf(Image/String): Get the index of the specified image or key name in the Images collection.
  • Remove(Image): Removes the specified image from the Images collection.
  • RemoveAt(int): Removes the image at the specified index from the Images collection.
  • RemoveByKey(string): Remove the image with the specified key name from the Images collection.
  • SetKeyName(int, string): Set a key name for the image at the specified index in the Images collection.

code example

namespace WinFormsTest
{
    public partial class frmImageList : Form
    {
        public frmImageList()
        {
            InitializeComponent();
        }

        private void frmImageList_Load(object sender, EventArgs e)
        {
            string imagedirPath = @"G:\Desktop\Images\";
            if (Directory.Exists(imagedirPath))
            {
                string[] stringsPath = Directory.GetFiles(imagedirPath);
                if (stringsPath.Length > 0)
                {
                    string[] fileType = { ".jpg", ".png" };
                    foreach (string s in stringsPath)
                    {
                        if (fileType.Contains(Path.GetExtension(s)))
                        {
                            Image image = Image.FromFile(s);
                            string keyName = Path.GetFileNameWithoutExtension(s);
                            imageList1.Images.Add(keyName, image);
                        }
                    }
                    imageList1.ImageSize = new Size(40, 40);
                    //使用imageList
                    label1.ImageList = imageList1;
                    label1.ImageKey = "1";
                    button1.ImageList = imageList1;
                    button1.ImageIndex = 2;
                }
            }
        }
    }
}

Insert image description here

3.ListView control

ListView group display

  • When adding items, you need to consider grouping and assign them to corresponding groups based on their names or numbers.
  • Establish grouping relationships, with group names and numbers respectively.
  • The relationship is stored, and when grouping, this relationship will prevail.

ListView application example

  • View modes: large icons, small icons, list, tiles, details.
  • Initialize the five implemented views.

ListView control

  • Attributes
    • ShowGroups: Whether to display groups
    • Groups: Group collection
    • Items: a collection of items
    • MultiSelect: Is it possible to select multiple times?
    • SmallImageList: ImageList control for all view images except large icon views
    • LargeImageList: ImageList control for large icon view images
    • AutoArrange: Whether to automatically arrange
    • CheckedIndices: Index of the selected item
    • CheckedItems: checked items
    • SelectedIndices: Index of the selected item
    • SelectedItems: selected items
  • method
    • Add: add items
    • Remove: Delete an item
    • Clear: Clear all items
  • event
    • SelectedIndexChanged: Selected item index change event
    • ColumnClick: Column click event
    • ItemChecked: item selected event

code example

namespace WinFormsTest
{
    public partial class frmListView : Form
    {
        public frmListView()
        {
            InitializeComponent();
        }
        Dictionary<string, string> dicGroup = new Dictionary<string, string>();
        private void frmListView_Load(object sender, EventArgs e)
        {
            LoadImgList(); //加载图片资源到imageList中
            //对ViewList进行分组
            lvList.Groups.Clear();
            lvList.Groups.Add(new ListViewGroup("熊大小时候", HorizontalAlignment.Center));
            lvList.Groups.Add(new ListViewGroup("哆啦A梦生气", HorizontalAlignment.Center));
            lvList.Groups.Add(new ListViewGroup("哆啦A梦吹口哨", HorizontalAlignment.Center));
            lvList.Items.Clear();
            //关系存储
            dicGroup.Add("熊大小时候", "1");
            dicGroup.Add("哆啦A梦生气", "2");
            dicGroup.Add("哆啦A梦吹口哨", "3");

            lvList.ShowGroups = true;
            //创建详细信息的表头
            lvList.Columns.Add("文件名", 100, HorizontalAlignment.Left);
            lvList.Columns.Add("创建日期", 160, HorizontalAlignment.Left);
            lvList.Columns.Add("类型", 60, HorizontalAlignment.Left);
            lvList.Columns.Add("大小", 60, HorizontalAlignment.Left);
            for (int i = 0; i < dic.Count; i++)
            {
                ListViewItem listViewItem = new ListViewItem();
                listViewItem.ImageIndex = i;
                listViewItem.Text = lglSmall.Images.Keys[i];
                listViewItem.SubItems.Add(File.GetCreationTime(dic[i]).ToString());//创建日期
                listViewItem.SubItems.Add(Path.GetExtension(dic[i]));//类型
                long length = new FileInfo(dic[i]).Length;//B
                listViewItem.SubItems.Add((length / 1024).ToString());//KB
                foreach (ListViewGroup lvgg in lvList.Groups)
                {
                    if (listViewItem.Text.Substring(0, 1) == dicGroup[lvgg.Header])
                    {
                        listViewItem.Group = lvgg;
                        break;
                    }
                }
                lvList.Items.Add(listViewItem);
            }
            lvList.View = View.LargeIcon; //制定初始的视图模式
            lvList.LargeImageList = lglLarge;
            lvList.SmallImageList = lglSmall;
        }

        Dictionary<int, string> dic = new Dictionary<int, string>();
        private void LoadImgList()
        {
            string path = @"G:\Desktop\Images";
            if (Directory.Exists(path))
            {
                string[] files = Directory.GetFiles(path);
                if (files.Length > 0)
                {
                    lglSmall.Images.Clear();
                    lglLarge.Images.Clear();
                    int index = 0;
                    string[] fileType = { ".jpg", ".png" };
                    foreach (string file in files)
                    {
                        if (fileType.Contains(Path.GetExtension(file)))
                        {
                            Image img = Image.FromFile(file);
                            string key = Path.GetFileNameWithoutExtension(file);
                            lglLarge.Images.Add(key, img);
                            lglSmall.Images.Add(key, img);
                            dic.Add(index, file);
                            index++;
                        }
                    }
                    lglLarge.ImageSize = new Size(50, 70);
                    lglSmall.ImageSize = new Size(20, 20);
                }
            }
        }
        private void btnLarge_Click(object sender, EventArgs e)
        {
            lvList.View = View.LargeIcon;
        }
        private void btnSmall_Click(object sender, EventArgs e)
        {
            lvList.View = View.SmallIcon;
        }
        private void btnList_Click(object sender, EventArgs e)
        {
            lvList.View = View.List;
        }
        private void btnDetail_Click(object sender, EventArgs e)
        {
            lvList.View = View.Details;
            lvList.GridLines = true;// 显示网格
        }
        private void btnTile_Click(object sender, EventArgs e)
        {
            lvList.View = View.Tile; //它的图标也使用的是LargeList
        }

        private void btnDivideOpen_Click(object sender, EventArgs e)
        {
            if (lvList.ShowGroups != true)
            {
                lvList.ShowGroups = true;
            }
        }

        private void btnDivideOff_Click(object sender, EventArgs e)
        {
            if (lvList.ShowGroups != false)
            {
                lvList.ShowGroups = false;
            }
        }
    }
}

Insert image description here

[WinForm Detailed Tutorial] How to obtain source code

Insert image description here

Excellent recommendations:
[C# Advanced 1] Array (Array), collection (ArrayList, Queue, Stack, HashList), List
[C# Advanced 8] Serialization and deserialization in C# (binary serialization, XML serialization and JSON serialization) a>

[Advanced C#] Summary of some common knowledge points in C# syntax
[WinForm detailed tutorial 1] Form, Label, TextBox and Button controls, RadioButton and CheckBox, ListBox
[WinForm Detailed Tutorial 3] NumericUpDown, PictureBox, RichTextBox and three Timer controls in WinForm

[C# Advanced] Delegates, events, callback functions, anonymous functions and lambda expressions in C#
I hope it helps, and you are welcome to follow me. I will update more later related information!

Guess you like

Origin blog.csdn.net/QH2107/article/details/134151206
Recommended