WindowsConsoleDriver.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using System;
  2. using System.IO;
  3. using System.Text;
  4. using BepInEx.ConsoleUtil;
  5. using UnityInjector.ConsoleUtil;
  6. namespace BepInEx
  7. {
  8. internal class WindowsConsoleDriver : IConsoleDriver
  9. {
  10. public TextWriter StandardOut { get; private set; }
  11. public TextWriter ConsoleOut { get; private set; }
  12. public bool ConsoleActive { get; private set; }
  13. public bool ConsoleIsExternal => true;
  14. public void Initialize(bool alreadyActive)
  15. {
  16. ConsoleActive = alreadyActive;
  17. StandardOut = Console.Out;
  18. }
  19. public void CreateConsole()
  20. {
  21. // On some Unity mono builds the SafeFileHandle overload for FileStream is missing
  22. // so we use the older but always included one instead
  23. #pragma warning disable 618
  24. ConsoleWindow.Attach();
  25. // If stdout exists, write to it, otherwise make it the same as console out
  26. // Not sure if this is needed? Does the original Console.Out still work?
  27. var stdout = ConsoleWindow.OriginalStdoutHandle != IntPtr.Zero ? ConsoleWindow.OriginalStdoutHandle : ConsoleWindow.ConsoleOutHandle;
  28. var originalOutStream = new FileStream(stdout, FileAccess.Write);
  29. StandardOut = new StreamWriter(originalOutStream, new UTF8Encoding(false))
  30. {
  31. AutoFlush = true
  32. };
  33. var consoleOutStream = new FileStream(ConsoleWindow.ConsoleOutHandle, FileAccess.Write);
  34. ConsoleOut = new StreamWriter(consoleOutStream, Console.OutputEncoding)
  35. {
  36. AutoFlush = true
  37. };
  38. ConsoleActive = true;
  39. #pragma warning restore 618
  40. }
  41. public void DetachConsole()
  42. {
  43. ConsoleWindow.Detach();
  44. ConsoleOut.Close();
  45. ConsoleOut = null;
  46. ConsoleActive = false;
  47. }
  48. public void SetConsoleColor(ConsoleColor color)
  49. {
  50. SafeConsole.ForegroundColor = color;
  51. Kon.ForegroundColor = color;
  52. }
  53. public void SetConsoleEncoding(uint codepage)
  54. {
  55. // Make sure of ConsoleEncoding helper class because on some Monos
  56. // Encoding.GetEncoding throws NotImplementedException on most codepages
  57. ConsoleEncoding.ConsoleCodePage = codepage;
  58. Console.OutputEncoding = ConsoleEncoding.GetEncoding(codepage);
  59. }
  60. public void SetConsoleTitle(string title)
  61. {
  62. ConsoleWindow.Title = title;
  63. }
  64. }
  65. }