You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
62 lines
2.0 KiB
62 lines
2.0 KiB
using System;
|
|
using System.IO;
|
|
using System.Text;
|
|
using System.Windows; // WPF 的核心命名空间
|
|
using System.Windows.Controls; // WPF TextBox 所在的命名空间
|
|
using System.Windows.Threading; // 用于 Dispatcher
|
|
|
|
namespace SunlightAggregationManager.UserClass
|
|
{
|
|
public class ControlWriter : TextWriter
|
|
{
|
|
private readonly TextBox _textbox;
|
|
|
|
public ControlWriter(TextBox textbox)
|
|
{
|
|
_textbox = textbox;
|
|
}
|
|
|
|
public override void Write(char value) => AppendText(DateTime.Now + ": " + value.ToString());
|
|
public override void Write(string? value) => AppendText(DateTime.Now + ": " + value);
|
|
public override void WriteLine(string? value) => AppendText(DateTime.Now + ": "+value + Environment.NewLine);
|
|
|
|
private void AppendText(string text)
|
|
{
|
|
if (!_textbox.Dispatcher.CheckAccess())
|
|
{
|
|
_textbox.Dispatcher.Invoke(DispatcherPriority.Background, new Action(() => AppendText(text)));
|
|
return;
|
|
}
|
|
_textbox.AppendText(text);
|
|
_textbox.ScrollToEnd();
|
|
}
|
|
|
|
public override Encoding Encoding => Encoding.UTF8;
|
|
}
|
|
|
|
//全局日志管理器
|
|
public static class GlobalLogManager
|
|
{
|
|
private static ControlWriter? _currentWriter;
|
|
|
|
// 【核心功能】注册目标 TextBox
|
|
// 子页面加载时调用这个方法
|
|
public static void RegisterTarget(TextBox logBox)
|
|
{
|
|
// 创建新的 Writer
|
|
_currentWriter = new ControlWriter(logBox);
|
|
|
|
// 【关键】将 Console 的输出重定向到这个 Writer
|
|
// 这样 Console.WriteLine("...") 就会自动写入到 logBox 中
|
|
Console.SetOut(_currentWriter);
|
|
|
|
Console.WriteLine("Start");
|
|
}
|
|
|
|
//提供一个直接写入的方法(如果不使用 Console.WriteLine)
|
|
public static void Write(string message)
|
|
{
|
|
_currentWriter?.WriteLine(message);
|
|
}
|
|
}
|
|
}
|
|
|