如何隐藏控制台窗口?

问题:我有一个不应该看到的控制台程序。 (它重置IIS并删除临时文件。)

现在我可以设法在开始后立即隐藏窗口,如下所示:

static void Main(string[] args) { var currentProcess = System.Diagnostics.Process.GetCurrentProcess(); Console.WriteLine(currentProcess.MainWindowTitle); IntPtr hWnd = currentProcess.MainWindowHandle;//FindWindow(null, "Your console windows caption"); //put your console window caption here if (hWnd != IntPtr.Zero) { //Hide the window ShowWindow(hWnd, 0); // 0 = SW_HIDE } 

问题是这显示了一秒钟的窗口。 是否有控制台程序的构造函数,我可以在显示之前隐藏窗口?

第二个:

我用

 [System.Runtime.InteropServices.DllImport("user32.dll")] static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); 

而且我不喜欢它里面的32。 没有DllImport有没有办法做到这一点?
一种.NET方式?

如果您不需要控制台(例如,用于Console.WriteLine ),则将应用程序构建选项更改为Windows应用程序。

这会更改.exe标头中的标志,以便Windows在应用程序启动时不会分配控制台会话。

如果我理解您的问题,只需手动创建控制台进程并隐藏控制台窗口:

 Process process = new Process(); process.StartInfo.FileName = "Bogus.exe"; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.CreateNoWindow = true; 

我为WPF应用程序执行此操作,该应用程序执行控制台应用程序(在后台工作程序中)并重定向标准输出,以便您可以在需要时在窗口中显示结果。 如果您需要查看更多代码(工作人员代码,重定向,参数传递等),请告诉我们。

 [DllImport("kernel32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool CloseHandle(IntPtr handle); [DllImport("kernel32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool FreeConsole(); [DllImport("kernel32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall, SetLastError = true)] private static extern IntPtr GetStdHandle([MarshalAs(UnmanagedType.I4)]int nStdHandle); // see the comment below private enum StdHandle { StdIn = -10, StdOut = -11, StdErr = -12 }; void HideConsole() { var ptr = GetStdHandle((int)StdHandle.StdOut); if (!CloseHandle(ptr)) throw new Win32Exception(); ptr = IntPtr.Zero; if (!FreeConsole()) throw new Win32Exception(); } 

在此处查看与控制台相关的更多API调用

  [DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); [DllImport("kernel32")] public static extern IntPtr GetConsoleWindow(); [DllImport("Kernel32")] private static extern bool SetConsoleCtrlHandler(EventHandler handler, bool add); static void Main(string[] args) { IntPtr hConsole = GetConsoleWindow(); if (IntPtr.Zero != hConsole) { ShowWindow(hConsole, 0); } } 

这应该做你的要求。