WindowsConsoleDriver.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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(Encoding encoding)
  54. {
  55. ConsoleEncoding.ConsoleCodePage = (uint)encoding.CodePage;
  56. Console.OutputEncoding = encoding;
  57. }
  58. public void SetConsoleTitle(string title)
  59. {
  60. ConsoleWindow.Title = title;
  61. }
  62. }
  63. }