WindowsConsoleDriver.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. // If stdout exists, write to it, otherwise make it the same as console out
  24. // Not sure if this is needed? Does the original Console.Out still work?
  25. var stdout = ConsoleWindow.OriginalStdoutHandle != IntPtr.Zero ? ConsoleWindow.OriginalStdoutHandle : ConsoleWindow.ConsoleOutHandle;
  26. var originalOutStream = new FileStream(new SafeFileHandle(stdout, false), FileAccess.Write);
  27. StandardOut = new StreamWriter(originalOutStream, new UTF8Encoding(false))
  28. {
  29. AutoFlush = true
  30. };
  31. var consoleOutStream = new FileStream(new SafeFileHandle(ConsoleWindow.ConsoleOutHandle, false), FileAccess.Write);
  32. ConsoleOut = new StreamWriter(consoleOutStream, Console.OutputEncoding)
  33. {
  34. AutoFlush = true
  35. };
  36. ConsoleActive = true;
  37. }
  38. public void DetachConsole()
  39. {
  40. ConsoleWindow.Detach();
  41. ConsoleOut.Close();
  42. ConsoleOut = null;
  43. ConsoleActive = false;
  44. }
  45. public void SetConsoleColor(ConsoleColor color)
  46. {
  47. SafeConsole.ForegroundColor = color;
  48. Kon.ForegroundColor = color;
  49. }
  50. public void SetConsoleEncoding(Encoding encoding)
  51. {
  52. ConsoleEncoding.ConsoleCodePage = (uint)encoding.CodePage;
  53. Console.OutputEncoding = encoding;
  54. }
  55. public void SetConsoleTitle(string title)
  56. {
  57. ConsoleWindow.Title = title;
  58. Console.Title = title;
  59. }
  60. }
  61. }