TextBoxWriter.cs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using System.Windows;
  8. using System.Windows.Controls;
  9. namespace EasyWeChatClient.Common
  10. {
  11. public class TextBoxWriter : TextWriter
  12. {
  13. TextBox textBox;
  14. delegate void WriteFunc(string value);
  15. WriteFunc write;
  16. WriteFunc writeLine;
  17. public TextBoxWriter(TextBox textBox)
  18. {
  19. this.textBox = textBox;
  20. write = Write;
  21. writeLine = WriteLine;
  22. }
  23. // 使用UTF-16避免不必要的编码转换
  24. public override Encoding Encoding
  25. {
  26. get { return Encoding.Unicode; }
  27. }
  28. // 最低限度需要重写的方法
  29. public override void Write(string value)
  30. {
  31. Application.Current.Dispatcher.Invoke(new Action(() =>
  32. {
  33. textBox.AppendText(value);
  34. }));
  35. }
  36. // 为提高效率直接处理一行的输出
  37. public override void WriteLine(string value)
  38. {
  39. Application.Current.Dispatcher.Invoke(new Action(() =>
  40. {
  41. textBox.AppendText(value);
  42. textBox.AppendText(this.NewLine);
  43. }));
  44. }
  45. }
  46. }