我创建了一个记录器模块文件类,并在类中对其进行了扩展,并添加了我自己的自定义StringBuilder
.我希望能够根据Logger类中每StringBuilder
行的 colored颜色 设置,轻松地为Form1设计器中的richTextBox1控件中的行着色.
在类Logger
中,我扩展了类以使用我自己的带有 colored颜色 属性的定制StringBuilder
.
// Logger.cs
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace Logger_Testing
{
public class Logger
{
private RichTextBox richTextBoxLogger;
private CustomStringBuilder sb = new CustomStringBuilder();
public Logger(RichTextBox richTextBoxLogger)
{
this.richTextBoxLogger = richTextBoxLogger;
}
public void LogStartDownload(string fileName, string fileUrl)
{
sb.AppendLine($"[Start Time]: {DateTime.Now}", Color.Yellow);
sb.AppendLine($"[File Name]: {fileName}", Color.Yellow);
sb.AppendLine($"[File URL]: {fileUrl}", Color.Yellow);
sb.AppendLine($"[Status] Downloading in progress", Color.Yellow);
}
public void LogDownloadProgress(double percentage, double speed, long totalBytes, long contentLength, TimeSpan elapsedTime)
{
this.elapsedTime = elapsedTime; // Store elapsed time for later use
sb.AppendLine($"[Progress]: {percentage}%", Color.Yellow);
sb.AppendLine($"[Downloaded]: {FormatBytes(totalBytes)} / {FormatBytes(contentLength)}", Color.Yellow);
sb.AppendLine($"[Download Speed]: {FormatBytes(speed)}/s", Color.Yellow);
sb.AppendLine($"[Time Elapsed]: {FormatTimeSpan(elapsedTime)}", Color.Yellow);
}
public void LogDownloadCompleted(bool isSuccess, TimeSpan elapsedTime, bool isCancelled)
{
this.elapsedTime = elapsedTime; // Update elapsed time when the download completes
if (!isCancelled)
{
sb.Replace($"[Status] Downloading in progress", $"[Status]: Download {(isSuccess ? "Completed Successfully" : "Failed")}", Color.Yellow);
}
else
{
sb.Replace($"[Status] Downloading in progress", $"[Status]: Download Cancelled", Color.Red);
}
sb.AppendLine($"[Elapsed Time]: {FormatTimeSpan(elapsedTime)}", Color.Yellow);
sb.AppendLine($"[End Time]: {DateTime.Now}", Color.Yellow);
sb.AppendLine("", Color.Yellow); // Add a space line between download logs
}
public void LogDownloadCompleted()
{
sb.AppendLine("[Status]: All downloads completed", Color.Yellow);
sb.AppendLine("", Color.Yellow);
}
public void LogDownloadCancelled()
{
sb.AppendLine("[Status]: Operation cancelled and all file have been deleted", Color.Yellow);
sb.AppendLine("", Color.Yellow);
}
public string GetLog(RichTextBox richTextBoxLogger)
{
richTextBoxLogger.Clear();
string log = sb.ToString();
richTextBoxLogger.AppendText(log); // Set RichTextBox text as RTF to preserve formatting
//logBuilder.Clear(); // Clear the log after appending it once
return log;
}
private string FormatBytes(double bytes)
{
const int scale = 1024;
string[] units = { "B", "KB", "MB", "GB", "TB", "PB", "EB" };
if (bytes <= 0)
{
return "0 B";
}
int magnitude = (int)Math.Floor(Math.Log(bytes, scale));
int index = Math.Min(magnitude, units.Length - 1);
double adjustedSize = bytes / Math.Pow(scale, index);
string format = (index >= 0 && index < 3) ? "F2" : "F0";
return $"{adjustedSize.ToString(format)} {units[index]}";
}
private string FormatTimeSpan(TimeSpan timeSpan)
{
return $"{timeSpan.Hours:D2}:{timeSpan.Minutes:D2}:{timeSpan.Seconds:D2}";
}
public void Replace(string oldText, string newText, Color textColor)
{
sb.Replace(oldText, newText, textColor);
UpdateRichTextBox();
}
private void UpdateRichTextBox()
{
richTextBoxLogger.Clear();
foreach (var line in sb.Lines)
{
richTextBoxLogger.SelectionStart = richTextBoxLogger.TextLength;
richTextBoxLogger.SelectionLength = 0;
richTextBoxLogger.SelectionColor = line.Color;
richTextBoxLogger.AppendText(line.Text + "\n");
richTextBoxLogger.SelectionColor = richTextBoxLogger.ForeColor; // Reset color
}
}
public class CustomStringBuilder
{
public List<CustomStringBuilderItem> Lines { get; } = new List<CustomStringBuilderItem>();
public void AppendLine(string text, Color color)
{
Lines.Add(new CustomStringBuilderItem { Text = text, Color = color });
}
public void Replace(string oldText, string newText, Color textColor)
{
var line = Lines.Find(l => l.Text.Contains(oldText));
if (line != null)
{
line.Text = line.Text.Replace(oldText, newText);
line.Color = textColor;
}
}
public override string ToString()
{
StringBuilder result = new StringBuilder();
foreach (var line in Lines)
{
result.AppendLine(line.Text);
}
return result.ToString();
}
}
public class CustomStringBuilderItem
{
public string Text { get; set; }
public Color Color { get; set; }
}
}
}
例如,我希望在Form1设计器中的richTextBox1中将该行显示为红色:
sb.Replace($"[Status] Downloading in progress", $"[Status]: Download Cancelled", Color.Red);
这是我在表格1中使用它的方式
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Logger_Testing
{
public partial class Form1 : Form
{
Logger logger;
private TimeSpan _elapsedTime;
public Form1()
{
InitializeComponent();
logger = new Logger(richTextBox1);
logger.LogStartDownload("Hello", "Hello World");
logger.GetLog(richTextBox1);
}
private void btnReplace_Click(object sender, EventArgs e)
{
logger.LogDownloadCompleted(false, _elapsedTime, true);
logger.LogDownloadCancelled();
logger.GetLog(richTextBox1);
}
}
}
但结果是,当我单击按钮替换文本时,替换的文本也是黄色的,就像richTextBox1中的所有其余文本一样,而不是特定替换行的红色.
行"[状态]:下载已取消"应为红色.