Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.IO;
- using Microsoft.Win32.SafeHandles;
- using System.Runtime.InteropServices;
- using System.Text;
- namespace DLL
- {
- /// <summary>
- /// Allocates and manages a new console for the calling process.
- /// </summary>
- public static class ConsoleCreator
- {
- [DllImport("kernel32.dll", EntryPoint = "AllocConsole", SetLastError = true, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
- private static extern int AllocConsole();
- [DllImport("kernel32.dll", EntryPoint = "FreeConsole", SetLastError = true, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
- private static extern int FreeConsole();
- [DllImport("kernel32.dll")]
- private static extern IntPtr GetConsoleWindow();
- #region hiding windows
- [DllImport("user32.dll")]
- private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
- private const int SW_HIDE = 0;
- private const int SW_SHOW = 5;
- #endregion
- [DllImport("kernel32.dll", EntryPoint = "GetStdHandle", SetLastError = true, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
- private static extern IntPtr GetStdHandle(int nStdHandle);
- private const int STD_OUTPUT_HANDLE = -11;
- /// <summary>
- /// Allocate new console.
- /// </summary>
- /// <exception cref="InvalidOperationException">Console already attached.</exception>
- public static void CreateConsoleWindow()
- {
- var handle = GetConsoleWindow();
- if (GetConsoleWindow() == IntPtr.Zero)
- {
- AllocConsole();
- IntPtr stdHandle = GetStdHandle(STD_OUTPUT_HANDLE);
- SafeFileHandle safeFileHandle = new SafeFileHandle(stdHandle, true);
- FileStream fileStream = new FileStream(safeFileHandle, FileAccess.Write);
- StreamWriter standardOutput = new StreamWriter(fileStream) { AutoFlush = true };
- Console.OutputEncoding = Encoding.UTF8;
- Console.SetOut(standardOutput);
- }
- else
- {
- throw new InvalidOperationException("Console already attached");
- }
- }
- /// <summary>
- /// Remove console.
- /// </summary>
- public static void RemoveConsoleWindow()
- {
- FreeConsole();
- //redirect output to standard output.
- var sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = true };
- Console.SetOut(sw);
- }
- /// <summary>
- /// Show console.
- /// </summary>
- public static void ShowConsoleWindow()
- {
- var handle = GetConsoleWindow();
- ShowWindow(handle, SW_SHOW);
- }
- /// <summary>
- /// Hide console.
- /// </summary>
- public static void HideConsoleWindow()
- {
- var handle = GetConsoleWindow();
- ShowWindow(handle, SW_HIDE);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement