using System.Diagnostics;
using System.Windows.Forms;
using System;

namespace pcmp
{
    public class TextTraceListener : TraceListener
    {
        TextBox _textbox = null;

        public TextTraceListener(TextBox textbox)
        {
            _textbox = textbox;
        }

        public override void Write(string message)
        {
            if (_textbox.InvokeRequired)
            {
                _textbox.Invoke((MethodInvoker)delegate { WriteToTextBox(message); });
            }
            else
            {
                WriteToTextBox(message);
            }
        }

        private void WriteToTextBox(string message)
        {
            _textbox.SelectionStart = _textbox.TextLength;
            _textbox.AppendText(DateTime.Now.ToString("[MM-dd HH:mm:ss]"));
            _textbox.AppendText(message);
        }

        public override void WriteLine(string message)
        {
            if (_textbox.InvokeRequired)
            {
                _textbox.Invoke((MethodInvoker)delegate { WriteLineToTextBox(message); });
            }
            else
            {
                WriteLineToTextBox(message);
            }
        }

        private void WriteLineToTextBox(string message)
        {
            _textbox.SelectionStart = _textbox.TextLength;
            _textbox.AppendText(DateTime.Now.ToString("[MM-dd HH:mm:ss]"));
            _textbox.AppendText(message);
            _textbox.AppendText("\r\n");
        }
    }
}
