使用AttachConsole,当我附加的进程正在运行并且喷出时,我仍然可以键入并运行其他命令

使用AttachConsole,当我附加的进程正在运行并且喷出时,我仍然可以键入并运行其他命令。

我的程序以表单或命令行运行。 如果以参数启动,它将在命令窗口中运行。 我使用AttachConsole(-1)将我的进程附加到我调用的命令窗口。 它工作得很好,我从我的过程中得到了所有的输出。

但是,控制台仍然处理来自键盘的用户输入,无论我输入什么,例如,如果我键入’cls’并按Enter键,输出将被擦除。 如何在进程运行时阻止用户对控制台的输入?

根据你正在做的事情,这可能不是很优雅,但在附加它后在控制台上执行Kill(),它将继续从你的其他进程获得输出。 下面的Windows窗体代码示例,添加您自己的铃声和口哨声:

using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Windows.Forms; namespace WindowsFormsApplication1 { internal static class Program { [DllImport("kernel32", SetLastError = true)] private static extern bool AttachConsole(int dwProcessId); [DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow(); [DllImport("user32.dll", SetLastError = true)] private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId); [STAThread] private static void Main(string[] args) { IntPtr ptr = GetForegroundWindow(); int u; GetWindowThreadProcessId(ptr, out u); Process process = Process.GetProcessById(u); AttachConsole(process.Id); process.Kill(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } } 

我发现一个更清洁的解决方案就是在程序退出后向控制台发送额外的“Enter”:

 [STAThread] public static int Main(string[] args) { try { AttachConsole(ATTACH_PARENT_PROCESS); ... ... } catch (Exception eCatchAll) { ShowHelpCommand.ShowHelp(eCatchAll.ToString()); return (int) ConsoleReturnCode.UnexpectedError; } finally { ConsoleNewLine(); } } private static void ConsoleNewLine() { try { // When using a winforms app with AttachConsole the app complets but there is no newline after the process stops. This gives the newline and looks normal from the console: SendKeys.SendWait("{ENTER}"); } catch (Exception e) { Debug.Fail(e.ToString()); } } 

对此不太确定但是AllocConsole而不是AttachConsole不是更容易解决这个问题的方法吗?