A fork of Eusth's IPA
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

69 行
2.6KB

  1. using System;
  2. using System.IO;
  3. using System.Runtime.InteropServices;
  4. using System.Text;
  5. namespace Windows
  6. {
  7. internal class GuiConsole
  8. {
  9. public static void CreateConsole()
  10. {
  11. if (hasConsole)
  12. return;
  13. if (oldOut == IntPtr.Zero)
  14. oldOut = GetStdHandle(-11);
  15. if (!AllocConsole())
  16. throw new Exception("AllocConsole() failed");
  17. conOut = CreateFile("CONOUT$", 0x40000000, 2, IntPtr.Zero, 3, 0, IntPtr.Zero);
  18. if (!SetStdHandle(-11, conOut))
  19. throw new Exception("SetStdHandle() failed");
  20. StreamToConsole();
  21. hasConsole = true;
  22. }
  23. public static void ReleaseConsole()
  24. {
  25. if (!hasConsole)
  26. return;
  27. if (!CloseHandle(conOut))
  28. throw new Exception("CloseHandle() failed");
  29. conOut = IntPtr.Zero;
  30. if (!FreeConsole())
  31. throw new Exception("FreeConsole() failed");
  32. if (!SetStdHandle(-11, oldOut))
  33. throw new Exception("SetStdHandle() failed");
  34. StreamToConsole();
  35. hasConsole = false;
  36. }
  37. private static void StreamToConsole()
  38. {
  39. Stream cstm = Console.OpenStandardOutput();
  40. StreamWriter cstw = new StreamWriter(cstm, Encoding.Default);
  41. cstw.AutoFlush = true;
  42. Console.SetOut(cstw);
  43. Console.SetError(cstw);
  44. }
  45. private static bool hasConsole = false;
  46. private static IntPtr conOut;
  47. private static IntPtr oldOut;
  48. [DllImport("kernel32.dll", SetLastError = true)]
  49. private static extern bool AllocConsole();
  50. [DllImport("kernel32.dll", SetLastError = false)]
  51. private static extern bool FreeConsole();
  52. [DllImport("kernel32.dll", SetLastError = true)]
  53. private static extern IntPtr GetStdHandle(int nStdHandle);
  54. [DllImport("kernel32.dll", SetLastError = true)]
  55. private static extern bool SetStdHandle(int nStdHandle, IntPtr hConsoleOutput);
  56. [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  57. private static extern IntPtr CreateFile(
  58. string fileName,
  59. int desiredAccess,
  60. int shareMode,
  61. IntPtr securityAttributes,
  62. int creationDisposition,
  63. int flagsAndAttributes,
  64. IntPtr templateFile);
  65. [DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true)]
  66. private static extern bool CloseHandle(IntPtr handle);
  67. }
  68. }