运行效果

核心代码
/// <summary>
/// 输出并设置字体颜色
/// </summary>
/// <param name="msg"></param>
/// <param name="color"></param>
private void WiterLog(string msg, Color color)
{
this.Invoke(new Action(() =>
{
txtBoxResultInfo.SuspendLayout();
txtBoxResultInfo.SelectionStart = txtBoxResultInfo.TextLength;
txtBoxResultInfo.SelectionLength = 0;
txtBoxResultInfo.SelectionColor = color;
txtBoxResultInfo.AppendText(msg + Environment.NewLine);
txtBoxResultInfo.SelectionColor = txtBoxResultInfo.ForeColor;
// 滚动到TextBox的最后一行
txtBoxResultInfo.ScrollToCaret();
txtBoxResultInfo.ResumeLayout();
}));
}
调用方法
private void button2_Click(object sender, EventArgs e)
{
WiterLog("abc",Color.Red);
}
完整代码
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 WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
/// <summary>
/// 输出并设置字体颜色
/// </summary>
/// <param name="msg"></param>
/// <param name="color"></param>
private void WiterLog(string msg, Color color)
{
this.Invoke(new Action(() =>
{
txtBoxResultInfo.SuspendLayout();
txtBoxResultInfo.SelectionStart = txtBoxResultInfo.TextLength;
txtBoxResultInfo.SelectionLength = 0;
txtBoxResultInfo.SelectionColor = color;
txtBoxResultInfo.AppendText(msg + Environment.NewLine);
txtBoxResultInfo.SelectionColor = txtBoxResultInfo.ForeColor;
// 滚动到TextBox的最后一行
txtBoxResultInfo.ScrollToCaret();
txtBoxResultInfo.ResumeLayout();
}));
}
private void button1_Click(object sender, EventArgs e)
{
Random rand = new Random();
for (int i = 1; i <= 50; i++)
{
// 生成随机颜色
Color randomColor = Color.FromArgb(
rand.Next(100, 256),
rand.Next(100, 256),
rand.Next(100, 256)
);
// 生成随机文字
string text = GenerateRandomString();
WiterLog($"{i}、{text}", randomColor);
}
}
private string GenerateRandomString()
{
Random rand = new Random();
int length = rand.Next(20, 50);
// 常见汉字字符集
string chineseChars = "的一是了我不人在有他这为之大来以个中上们到说国和地也子时道出而于就得里后自之者发经行家方如事成";
// 生成随机中文字符
char[] chars = new char[length];
for (int i = 0; i < length; i++)
{
chars[i] = chineseChars[rand.Next(chineseChars.Length)];
}
return new string(chars);
}
private void button2_Click(object sender, EventArgs e)
{
WiterLog("abc",Color.Red);
}
}
}
参考连接
特此记录
anlog
2025年8月17日
1万+

被折叠的 条评论
为什么被折叠?



