如何将输入发送到控制台,就像用户正在键入一样?

时间:2009-01-16 17:12:13

标签: .net automation cmd stdin

这是我的问题。我有一个必须在TTY中运行的程序,cygwin提供了这个TTY。当我重定向stdIn程序失败,因为它没有TTY。我不能修改这个程序,需要一些自动化方法。

如何抓取cmd.exe窗口并发送数据并让用户认为用户输入数据?

我正在使用C#,我相信有一种方法可以使用java.awt.Robot,但我必须使用C#,原因是其他原因。

4 个答案:

答案 0 :(得分:5)

我已经想出了如何将输入发送到控制台。我使用了Jon Skeet所说的话。我并非100%确定这是实现此目的的正确方法。

如果有任何评论可以让这更好,我很乐意来到这里。我这样做只是为了看看能否解决它。

这是我盯着等待用户输入的程序

class Program
{
    static void Main(string[] args)
    {
        // This is needed to wait for the other process to wire up.
        System.Threading.Thread.Sleep(2000);

        Console.WriteLine("Enter Pharse: ");

        string pharse = Console.ReadLine();

        Console.WriteLine("The password is '{0}'", pharse);


        Console.WriteLine("Press any key to exit. . .");
        string lastLine = Console.ReadLine();

        Console.WriteLine("Last Line is: '{0}'", lastLine);
    }
}

这是控制台应用程序写入另一个

class Program
{
    static void Main(string[] args)
    {
        // Find the path of the Console to start
        string readFilePath = System.IO.Path.GetFullPath(@"..\..\..\ReadingConsole\bin\Debug\ReadingConsole.exe");

        ProcessStartInfo startInfo = new ProcessStartInfo(readFilePath);

        startInfo.RedirectStandardOutput = true;
        startInfo.RedirectStandardInput = true;
        startInfo.WindowStyle = ProcessWindowStyle.Hidden;
        startInfo.CreateNoWindow = true;
        startInfo.UseShellExecute = false;

        Process readProcess = new Process();
        readProcess.StartInfo = startInfo;

        // This is the key to send data to the server that I found
        readProcess.OutputDataReceived += new DataReceivedEventHandler(readProcess_OutputDataReceived);

        // Start the process
        readProcess.Start();

        readProcess.BeginOutputReadLine();

        // Wait for other process to spin up
        System.Threading.Thread.Sleep(5000);

        // Send Hello World
        readProcess.StandardInput.WriteLine("Hello World");

        readProcess.StandardInput.WriteLine("Exit");

        readProcess.WaitForExit();
    }

    static void readProcess_OutputDataReceived(object sender, DataReceivedEventArgs e)
    {
        // Write what was sent in the event
        Console.WriteLine("Data Recieved at {1}: {0}", e.Data, DateTime.UtcNow.Ticks);
    }
}

答案 1 :(得分:1)

您可以使用ProcessStartInfo.RedirectStandardInput(和输出/错误)来控制数据流,从而在代码中启动程序(或cygwin)吗?

答案 2 :(得分:1)

这听起来像SendKeys()的任务。它不是C#,而是VBScript,但是 - 你要求 smoke 自动化它的方式:

Set Shell = CreateObject("WScript.Shell")

Shell.Run "cmd.exe /k title RemoteControlShell"
WScript.Sleep 250

Shell.AppActivate "RemoteControlShell"
WScript.Sleep 250

Shell.SendKeys "dir{ENTER}"

答案 3 :(得分:0)

前段时间我有类似的问题,cygwin应该把一些有用的信息(确切的cygwin函数,错误文本和WINAPI错误代码)写入错误流,你应该将它重定向到某个地方并读取它写的内容。

相关问题