Server/RichTextBoxTextWriter.cs
author StephaneLenclud
Tue, 16 Aug 2016 12:25:20 +0200
changeset 234 0c75dec19d39
parent 206 33be8cb90c57
permissions -rw-r--r--
Ear cleanup.
     1 using System;
     2 using System.Text;
     3 using System.IO;
     4 using System.Windows.Forms;
     5 
     6 namespace SharpDisplayManager
     7 {
     8     public class RichTextBoxTextWriter : TextWriter
     9     {
    10         public delegate void WriteDelegate(char aChar);
    11 
    12         RichTextBox iRichTextBox = null;
    13         string iAccumulator = "";
    14         private char iLastChar='\n';
    15 
    16         public RichTextBoxTextWriter(RichTextBox aRichTextBox)
    17         {
    18             iRichTextBox = aRichTextBox;            
    19         }
    20 
    21         public override void Write(char aChar)
    22         {
    23             if (aChar == '\r')
    24             {
    25                 //Skip
    26                 return;
    27             }
    28 
    29             //Put our time stamp if starting a new line
    30             char previousChar = iLastChar;
    31             iLastChar = aChar;
    32             if (previousChar == '\n')
    33             {
    34                 //Write(DateTime.Now.ToString("yyyy/MM/dd - HH:mm:ss.fff: "));
    35                 Write(DateTime.Now.ToString("MM/dd HH:mm:ss.fff: "));
    36             }
    37 
    38             
    39             base.Write(aChar);
    40             if (iRichTextBox.InvokeRequired)
    41             {
    42                 lock (iAccumulator)
    43                 {
    44                     iAccumulator += aChar;
    45                 }
    46                 
    47                 //Invoke was not working from here
    48                 //WriteDelegate d = new WriteDelegate(Write);
    49                 //iRichTextBox.Invoke(d, new object[] { aChar });
    50             }
    51             else
    52             {
    53                 Flush();
    54                 iRichTextBox.AppendText(aChar.ToString()); // When character data is written, append it to the text box.
    55             }
    56         }
    57 
    58         public override Encoding Encoding
    59         {
    60             get { return System.Text.Encoding.UTF8; }
    61         }
    62 
    63         /// <summary>
    64         /// 
    65         /// </summary>
    66         public override void Flush()
    67         {
    68             base.Flush();
    69 
    70             lock (iAccumulator)
    71             {
    72                 if (!string.IsNullOrEmpty(iAccumulator))
    73                 {
    74                     iRichTextBox.AppendText(iAccumulator); // When character data is written, append it to the text box.
    75                     iAccumulator = "";
    76                 }
    77             }
    78 
    79         }
    80     }
    81 }