Server/RichTextBoxTextWriter.cs
author Stephane Lenclud
Mon, 18 Jul 2016 15:56:25 +0200
changeset 205 127382a596e7
child 206 33be8cb90c57
permissions -rw-r--r--
Published v0.9.2.0
Stephane@202
     1
using System;
Stephane@202
     2
using System.Text;
Stephane@202
     3
using System.IO;
Stephane@202
     4
using System.Windows.Forms;
Stephane@202
     5
Stephane@202
     6
namespace SharpDisplayManager
Stephane@202
     7
{
Stephane@202
     8
    public class RichTextBoxTextWriter : TextWriter
Stephane@202
     9
    {
Stephane@202
    10
        public delegate void WriteDelegate(char aChar);
Stephane@202
    11
Stephane@202
    12
        RichTextBox iRichTextBox = null;
Stephane@202
    13
        string iAccumulator = "";
Stephane@202
    14
Stephane@202
    15
        public RichTextBoxTextWriter(RichTextBox aRichTextBox)
Stephane@202
    16
        {
Stephane@202
    17
            iRichTextBox = aRichTextBox;
Stephane@202
    18
        }
Stephane@202
    19
Stephane@202
    20
        public override void Write(char aChar)
Stephane@202
    21
        {
Stephane@202
    22
            base.Write(aChar);
Stephane@202
    23
            if (iRichTextBox.InvokeRequired)
Stephane@202
    24
            {
Stephane@202
    25
                lock (iAccumulator)
Stephane@202
    26
                {
Stephane@202
    27
                    iAccumulator += aChar;
Stephane@202
    28
                }
Stephane@202
    29
                
Stephane@202
    30
                //WriteDelegate d = new WriteDelegate(Write);
Stephane@202
    31
                //iRichTextBox.Invoke(d, new object[] { aChar });
Stephane@202
    32
            }
Stephane@202
    33
            else
Stephane@202
    34
            {
Stephane@202
    35
                Flush();
Stephane@202
    36
                iRichTextBox.AppendText(aChar.ToString()); // When character data is written, append it to the text box.
Stephane@202
    37
            }            
Stephane@202
    38
        }
Stephane@202
    39
Stephane@202
    40
        public override Encoding Encoding
Stephane@202
    41
        {
Stephane@202
    42
            get { return System.Text.Encoding.UTF8; }
Stephane@202
    43
        }
Stephane@202
    44
Stephane@202
    45
        public void FlushAccumulator()
Stephane@202
    46
        {
Stephane@202
    47
            lock (iAccumulator)
Stephane@202
    48
            {
Stephane@202
    49
                if (!string.IsNullOrEmpty(iAccumulator))
Stephane@202
    50
                {
Stephane@202
    51
                    iRichTextBox.AppendText(iAccumulator); // When character data is written, append it to the text box.
Stephane@202
    52
                    iAccumulator = "";
Stephane@202
    53
                }
Stephane@202
    54
Stephane@202
    55
            }
Stephane@202
    56
Stephane@202
    57
        }
Stephane@202
    58
    }
Stephane@202
    59
}