Cardlife mod patcher
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ConsoleWindow.cs 2.9KB

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