WindowsConsoleDriver.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using System;
  2. using System.IO;
  3. using System.Text;
  4. using BepInEx.ConsoleUtil;
  5. using Microsoft.Win32.SafeHandles;
  6. using UnityInjector.ConsoleUtil;
  7. namespace BepInEx
  8. {
  9. internal class WindowsConsoleDriver : IConsoleDriver
  10. {
  11. public TextWriter StandardOut { get; private set; }
  12. public TextWriter ConsoleOut { get; private set; }
  13. public bool ConsoleActive { get; private set; }
  14. public bool ConsoleIsExternal => true;
  15. public void Initialize(bool alreadyActive)
  16. {
  17. ConsoleActive = alreadyActive;
  18. StandardOut = Console.Out;
  19. }
  20. public void CreateConsole()
  21. {
  22. ConsoleWindow.Attach();
  23. // Not sure if this is needed? Does the original Console.Out still work?
  24. var originalOutStream = new FileStream(new SafeFileHandle(ConsoleWindow.OriginalStdoutHandle, false), FileAccess.Write);
  25. StandardOut = new StreamWriter(originalOutStream, new UTF8Encoding(false))
  26. {
  27. AutoFlush = true
  28. };
  29. var consoleOutStream = new FileStream(new SafeFileHandle(ConsoleWindow.ConsoleOutHandle, false), FileAccess.Write);
  30. ConsoleOut = new StreamWriter(consoleOutStream, Console.OutputEncoding)
  31. {
  32. AutoFlush = true
  33. };
  34. ConsoleActive = true;
  35. }
  36. public void DetachConsole()
  37. {
  38. ConsoleWindow.Detach();
  39. ConsoleOut.Close();
  40. ConsoleOut = null;
  41. ConsoleActive = false;
  42. }
  43. public void SetConsoleColor(ConsoleColor color)
  44. {
  45. SafeConsole.ForegroundColor = color;
  46. Kon.ForegroundColor = color;
  47. }
  48. public void SetConsoleEncoding(Encoding encoding)
  49. {
  50. ConsoleEncoding.ConsoleCodePage = (uint)encoding.WindowsCodePage;
  51. Console.OutputEncoding = encoding;
  52. }
  53. public void SetConsoleTitle(string title)
  54. {
  55. ConsoleWindow.Title = title;
  56. Console.Title = title;
  57. }
  58. }
  59. }