我正在开发的程序可以使用CMD命令行启动,使用以下代码:
string[] commandLines = Environment.GetCommandLineArgs();
然而,我希望在处理完命令行后能够返回消息给CMD窗口。感谢您的帮助。
编辑:我正在以Windows应用程序而不是控制台应用程序运行该程序。
我正在开发的程序可以使用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.");
[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}");
}
}
}
stdout
不够用的原因是什么? - IllusiveBrian