如何回显现有的CMD窗口

所以我正在使用的程序可以使用以下代码在CMD中使用命令行启动。

string[] commandLines = Environment.GetCommandLineArgs(); 

但是我希望能够在处理命令行之后将消息返回到CMD窗口。 任何帮助,将不胜感激。

编辑:我将程序作为Windows应用程序运行,而不是控制台应用程序。

我最后使用RenniePet发布的答案作为对我的问题的评论来解决问题。 我会在这里列出解决方案,以便任何试图重现它的人。

 [System.Runtime.InteropServices.DllImport("kernel32.dll")] private static extern bool AttachConsole(int dwProcessId); private const int ATTACH_PARENT_PROCESS = -1; StreamWriter _stdOutWriter; // this must be called early in the program public void GUIConsoleWriter() { // this needs to happen before attachconsole. // If the output is not redirected we still get a valid stream but it doesn't appear to write anywhere // I guess it probably does write somewhere, but nowhere I can find out about var stdout = Console.OpenStandardOutput(); _stdOutWriter = new StreamWriter(stdout); _stdOutWriter.AutoFlush = true; AttachConsole(ATTACH_PARENT_PROCESS); } public void WriteLine(string line) { GUIConsoleWriter(); _stdOutWriter.WriteLine(line); Console.WriteLine(line); } 

将此代码添加到程序后,您只需使用例如以下内容开始返回行。

 WriteLine("\nExecuting commands."); 

您可以使用.NET SendKeys类将键击发送到您不拥有的应用程序。 目标应用程序必须处于活动状态才能检索击键。 因此,在发送之前,您必须激活目标应用程序。 您可以通过获取窗口的句柄并使用句柄将SetForegroundWindow进行assembly来实现。

以下是一些示例代码,可帮助您入门:

  [DllImport("user32.dll", EntryPoint = "FindWindow")] private static extern IntPtr FindWindow(string lp1, string lp2); [DllImport("user32.dll", ExactSpelling = true, CharSet = CharSet.Auto)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool SetForegroundWindow(IntPtr hWnd); private void button1_Click(object sender, EventArgs e) { IntPtr handle = FindWindow("ConsoleWindowClass", "Eingabeaufforderung"); if (!handle.Equals(IntPtr.Zero)) { if (SetForegroundWindow(handle)) { // send SendKeys.Send("Greetings from Postlagerkarte!"); // send key "Enter" SendKeys.Send("{ENTER}"); } } } 

如果运行控制台应用程序,您希望使用Console类与其进行交互。

 Console.WriteLine("Text"); 

如果您正在运行Windows窗体应用程序,请阅读此处 。