using System.Windows; namespace Serein.WorkBench { /// /// DebugWindow.xaml 的交互逻辑 /// using System; using System.Text; using System.Threading.Tasks; using System.Timers; using System.Windows; public partial class LogWindow : Window { private StringBuilder logBuffer = new StringBuilder(); private int logUpdateInterval = 100; // 批量更新的时间间隔(毫秒) private Timer logUpdateTimer; private const int MaxLines = 1000; // 最大显示的行数 private bool autoScroll = true; // 自动滚动标识 public LogWindow() { InitializeComponent(); // 初始化定时器,用于批量更新日志 logUpdateTimer = new Timer(logUpdateInterval); logUpdateTimer.Elapsed += (s, e) => FlushLog(); // 定时刷新日志 logUpdateTimer.Start(); // 添加滚动事件处理,判断用户是否手动滚动 // LogTextBox.ScrollChanged += LogTextBox_ScrollChanged; } /// /// 添加日志到缓冲区 /// public void AppendText(string text) { lock (logBuffer) { logBuffer.Append(text); // 将日志添加到缓冲区中 } } /// /// 清空日志缓冲区并更新到 TextBox 中 /// private void FlushLog() { if (logBuffer.Length == 0) return; Dispatcher.Invoke(() => { lock (logBuffer) { LogTextBox.AppendText(logBuffer.ToString()); logBuffer.Clear(); // 清空缓冲区 } TrimLog(); // 检查并修剪日志长度 ScrollToEndIfNeeded(); // 根据条件滚动到末尾 }); } /// /// 限制日志输出的最大行数,超出时删除旧日志 /// private void TrimLog() { if (LogTextBox.LineCount > MaxLines) { // 删除最早的多余行 LogTextBox.Text = LogTextBox.Text.Substring(LogTextBox.GetCharacterIndexFromLineIndex(LogTextBox.LineCount - MaxLines)); } } /// /// 检测用户是否手动滚动了文本框 /// private void LogTextBox_ScrollChanged(object sender, System.Windows.Controls.ScrollChangedEventArgs e) { if (e.ExtentHeightChange == 0) // 用户手动滚动时 { // 判断是否滚动到底部 // autoScroll = LogTextBox.VerticalOffset == LogTextBox.ScrollableHeight; } } /// /// 根据 autoScroll 标志决定是否滚动到末尾 /// private void ScrollToEndIfNeeded() { if (autoScroll) { LogTextBox.ScrollToEnd(); // 仅在需要时滚动到末尾 } } /// /// 清空日志 /// public void Clear() { Dispatcher.BeginInvoke(() => { LogTextBox.Clear(); }); } /// /// 点击清空日志按钮时触发 /// private void ClearLog_Click(object sender, RoutedEventArgs e) { LogTextBox.Clear(); } /// /// 窗口关闭事件,隐藏窗体而不是关闭 /// private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) { //logUpdateTimer?.Stop(); //logUpdateTimer?.Close(); //logUpdateTimer?.Dispose(); logBuffer?.Clear(); Clear(); e.Cancel = true; // 取消关闭操作 this.Hide(); // 隐藏窗体而不是关闭 } } }