添加刷新逻辑
This commit is contained in:
1 parent
f40e9db080
commit
dcfa96824f
13 files changed
+875
No files matched your search
@@ -0,0 +1,69 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Windows; // WPF 的核心命名空间
|
||||
using System.Windows.Controls; // WPF TextBox 所在的命名空间
|
||||
using System.Windows.Threading; // 用于 Dispatcher
|
||||
|
||||
namespace ForwardingServerUI.Class
|
||||
{
|
||||
public class ControlWriter : TextWriter
|
||||
{
|
||||
private readonly TextBox _textbox;
|
||||
private readonly Action<string> _logGingDataAction;
|
||||
|
||||
public ControlWriter(TextBox textbox,Action<string> logGingDataAction)
|
||||
{
|
||||
_textbox = textbox;
|
||||
_logGingDataAction = logGingDataAction;
|
||||
}
|
||||
|
||||
public override void Write(char value) => AppendText(DateTime.Now + ": " + value.ToString(), true);
|
||||
public override void Write(string? value) => AppendText(DateTime.Now + ": " + value, true);
|
||||
public override void WriteLine(string? value) => AppendText(DateTime.Now + ": "+value + Environment.NewLine, true);
|
||||
|
||||
private void AppendText(string text, bool invokeExternalLog)
|
||||
{
|
||||
if (!_textbox.Dispatcher.CheckAccess())
|
||||
{
|
||||
_textbox.Dispatcher.Invoke(DispatcherPriority.Background, new Action(() => AppendText(text, true)));
|
||||
return;
|
||||
}
|
||||
_textbox.AppendText(text);
|
||||
_textbox.ScrollToEnd();
|
||||
|
||||
if (invokeExternalLog)
|
||||
{
|
||||
_logGingDataAction?.Invoke(text);
|
||||
}
|
||||
}
|
||||
|
||||
public override Encoding Encoding => Encoding.UTF8;
|
||||
}
|
||||
|
||||
//全局日志管理器
|
||||
public static class GlobalLogManager
|
||||
{
|
||||
private static ControlWriter? _currentWriter;
|
||||
|
||||
// 【核心功能】注册目标 TextBox
|
||||
// 子页面加载时调用这个方法
|
||||
public static void RegisterTarget(TextBox logBox ,Action<string> logGingDataAction)
|
||||
{
|
||||
// 创建新的 Writer
|
||||
_currentWriter = new ControlWriter(logBox, logGingDataAction);
|
||||
|
||||
// 【关键】将 Console 的输出重定向到这个 Writer
|
||||
// 这样 Console.WriteLine("...") 就会自动写入到 logBox 中
|
||||
Console.SetOut(_currentWriter);
|
||||
|
||||
Console.WriteLine("Start");
|
||||
}
|
||||
|
||||
//提供一个直接写入的方法(如果不使用 Console.WriteLine)
|
||||
public static void Write(string message)
|
||||
{
|
||||
_currentWriter?.WriteLine(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user