SafeConsole.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // --------------------------------------------------
  2. // UnityInjector - SafeConsole.cs
  3. // Copyright (c) Usagirei 2015 - 2015
  4. // --------------------------------------------------
  5. using System;
  6. using System.Reflection;
  7. namespace UnityInjector.ConsoleUtil
  8. {
  9. public static class SafeConsole
  10. {
  11. private static GetColorDelegate _getBackgroundColor;
  12. private static GetColorDelegate _getForegroundColor;
  13. private static SetColorDelegate _setBackgroundColor;
  14. private static SetColorDelegate _setForegroundColor;
  15. public static ConsoleColor BackgroundColor
  16. {
  17. get { return _getBackgroundColor(); }
  18. set { _setBackgroundColor(value); }
  19. }
  20. public static ConsoleColor ForegroundColor
  21. {
  22. get { return _getForegroundColor(); }
  23. set { _setForegroundColor(value); }
  24. }
  25. static SafeConsole()
  26. {
  27. var tConsole = typeof(Console);
  28. InitColors(tConsole);
  29. }
  30. private static void InitColors(Type tConsole)
  31. {
  32. const BindingFlags BINDING_FLAGS = BindingFlags.Public | BindingFlags.Static;
  33. var sfc = tConsole.GetMethod("set_ForegroundColor", BINDING_FLAGS);
  34. var sbc = tConsole.GetMethod("set_BackgroundColor", BINDING_FLAGS);
  35. var gfc = tConsole.GetMethod("get_ForegroundColor", BINDING_FLAGS);
  36. var gbc = tConsole.GetMethod("get_BackgroundColor", BINDING_FLAGS);
  37. _setForegroundColor = sfc != null
  38. ? (SetColorDelegate)Delegate.CreateDelegate(typeof(SetColorDelegate), sfc)
  39. : (value => { });
  40. _setBackgroundColor = sbc != null
  41. ? (SetColorDelegate)Delegate.CreateDelegate(typeof(SetColorDelegate), sbc)
  42. : (value => { });
  43. _getForegroundColor = gfc != null
  44. ? (GetColorDelegate)Delegate.CreateDelegate(typeof(GetColorDelegate), gfc)
  45. : (() => ConsoleColor.Gray);
  46. _getBackgroundColor = gbc != null
  47. ? (GetColorDelegate)Delegate.CreateDelegate(typeof(GetColorDelegate), gbc)
  48. : (() => ConsoleColor.Black);
  49. }
  50. private delegate ConsoleColor GetColorDelegate();
  51. private delegate void SetColorDelegate(ConsoleColor value);
  52. }
  53. }