winforms 如何创建一个类来用颜色和更多属性来格式化标签文本以显示信息?

ohtdti5x  于 2023-10-23  发布在  其他
关注(0)|答案(1)|浏览(74)

这是我试图用标签显示的示例:这还不准确,应该是一行一行的,每一行都从同一个位置开始.
数据应该是红色文本应该是绿色。

首先是红色的下载进度:根本不应该显示。
剩下的都是一行一行的但都是红色的文本大小:应该是绿色的1.211 MB红色的文本已下载:绿色和0.727 MB红色绿色4红色速度:绿色1.79 MB/s红色
我尝试创建一个模块类:

using System;
using System.Text;

public static class DownloadProgressFormatter
{
    public static string FormatDownloadProgress(double totalMBs, double downloadedMBs, int imagesLeft, double speed)
    {
        StringBuilder progressBuilder = new StringBuilder();

        Console.ForegroundColor = ConsoleColor.Green;
        progressBuilder.AppendLine("Download Progress:");
        Console.ForegroundColor = ConsoleColor.Red;
        progressBuilder.AppendLine($"   Size: {totalMBs} MB");
        progressBuilder.AppendLine($"   Downloaded: {downloadedMBs} MB");
        Console.ForegroundColor = ConsoleColor.Green;
        progressBuilder.AppendLine($"   Images Left: {imagesLeft}");
        Console.ForegroundColor = ConsoleColor.Red;
        progressBuilder.AppendLine($"   Speed: {speed} MB/s");

        Console.ResetColor();

        return progressBuilder.ToString();
    }
}

然后在form 1中使用它:

private async Task DownloadImages(List<string> links)
        {
            int totalLinks = links.Count;
            int downloadedCount = 0;

            for (int i = 0; i < links.Count; i++)
            {
                string link = links[i];
                using (var client = new WebClient())
                {
                    client.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36");

                    Stopwatch sw = Stopwatch.StartNew();
                    byte[] data = await client.DownloadDataTaskAsync(link);
                    sw.Stop();

                    string outputFolder = Properties.Settings.Default.SatelliteFolder;
                    string extension = ".png";
                    string filename = $"Satellite_{(i + 1).ToString("000")}{extension}";
                    string fullPath = Path.Combine(outputFolder, filename);

                    // Write the bytes to a file
                    using (FileStream stream = new FileStream(fullPath, FileMode.Create))
                    {
                        await stream.WriteAsync(data, 0, data.Length);
                    }

                    downloadedCount++;

                    // Calculate download progress information
                    int imagesLeft = totalLinks - downloadedCount;
                    double totalMBs = Math.Round((double)totalLinks * data.Length / 1024.0 / 1024.0, 3);
                    double downloadedMBs = Math.Round((double)downloadedCount * data.Length / 1024.0 / 1024.0, 3);
                    double speed = Math.Round((double)data.Length / 1024.0 / 1024.0 / sw.Elapsed.TotalSeconds, 3);

                    string progress = DownloadProgressFormatter.FormatDownloadProgress(totalMBs, downloadedMBs, imagesLeft, speed);
                    lblDownloadProgress.Text = progress;
                    lblDownloadProgress.Font = new Font(lblDownloadProgress.Font, FontStyle.Bold);

                    // Update progress bar
                    progressBar1.Value = (int)((double)downloadedCount / totalLinks * 100);

                    // Load the image from memory
                    Image image;
                    using (MemoryStream ms = new MemoryStream(data))
                    {
                        image = Image.FromStream(ms);
                    }

                    // Add the image to the downloadImages list
                    downloadedImages.Add(image);

                    // Update the picture box with the latest image
                    pictureBox1.Image = image;
                    pictureBox1.Refresh();

                    await Task.Delay(100);
                }
            }

            // Start the timer to display the downloaded images
            timer1.Enabled = true;
        }

部分:

// Calculate download progress information
                    int imagesLeft = totalLinks - downloadedCount;
                    double totalMBs = Math.Round((double)totalLinks * data.Length / 1024.0 / 1024.0, 3);
                    double downloadedMBs = Math.Round((double)downloadedCount * data.Length / 1024.0 / 1024.0, 3);
                    double speed = Math.Round((double)data.Length / 1024.0 / 1024.0 / sw.Elapsed.TotalSeconds, 3);

                    string progress = DownloadProgressFormatter.FormatDownloadProgress(totalMBs, downloadedMBs, imagesLeft, speed);
                    lblDownloadProgress.Text = progress;
                    lblDownloadProgress.Font = new Font(lblDownloadProgress.Font, FontStyle.Bold);

但都是红色的每个属性的文本应该是绿色。
显示信息的标签为lblDownloadProgress

piztneat

piztneat1#

正如在注解中已经提到的,Label控件不能有不同颜色的文本,除非它是一个自定义实现。
您可能需要考虑FlowLayoutPanelTableLayoutPanel作为替代方案。下面是FlowLayoutPanel的示例。此示例中的每一行都由两个Label类型的控件组成。换行符是以编程方式添加的。找到下面的评论。

using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;

namespace Test
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            var flp = new FlowLayoutPanel
            {
                Width = 400,
                Height = 200,
                Location = new Point(10, 10)
            };
            Controls.Add(flp);

            // Put the labels to the dictionary for better processing.
            var labels = new Dictionary<string, string>
            {
                { "Size:", "1.211 MB" },
                { "Downloaded:", "0.727 MB" },
                { "Images left:", "4" },
                { "Speed:", "1.79 MB/s" },
            };

            // Go through each label
            foreach (var line in labels)
            {
                // Each line consists of two labels: Text + Value
                // Each label has its own color.
                flp.Controls.Add(new Label() { Text = line.Key, ForeColor = Color.Green });
                flp.Controls.Add(new Label() { Text = line.Value, ForeColor = Color.Red });

                // Break after each line
                flp.SetFlowBreak(flp.Controls[flp.Controls.Count - 1], true);
            }
        }
    }
}

它给出以下输出:

相关问题