Arun E
Arun E

Reputation: 41

Read/Write data to Console generated by exe from windows form application

I have a simple c# windowsform application which calls an exe .The exe inturn opens a console. Is it possible to read and write data to the CONSOLE generated by the exe. I want to send data from my windows forms application

Upvotes: 0

Views: 1633

Answers (2)

Kavindu Dodanduwa
Kavindu Dodanduwa

Reputation: 13077

You can pass arguments using Process.startInfo(). And obtaining parameters should be done according to your requirement (may be reading from textbox etc.)

        // Extracting parameter from form
        string para1=textbox1.Text;

        // State the program to be start; PATH is the path to program .exe
        ProcessStartInfo startInfo = new ProcessStartInfo(PATH);

        // Passing arguments :para1 extracted from textbox (string type) 
        startInfo.Arguments = para1 

        // Starting process
        Process exec= Process.Start(startInfo);

        // optionally waiting for execution
        exec.WaitForExit();

Also this can be done in single line as follows,

// Simply define program to execute and pass a and b parameters
Process.Start(PATH,para1);

Note : path is a string like "program1.exe" or full path to your program

Additionally : You are not LIMITED to one parameter

        // Extracting parameter from form
        string para1=textbox1.Text;
        string para2=textbox2.Text;

        Process.Start(PATH,para1+" "+para2); // Pass 2 parameters (using + string concat)

You can send many parameters simply separating them by spaces.. When you need to include space in parameter simply escape them using '\'

Upvotes: 1

Phil Wright
Phil Wright

Reputation: 22956

If your executable is creating the console by using a Process instance that runs 'cmd.exe' then you can redirect the input and output of the console by setting the StartupInfo of the Process...

p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardInput = true;

...then you can hook into an event the occurs when user enters console input...

p.OutputDataReceived += new .DataReceivedEventHandler(ConsoleOutputHandler);

void ConsoleOutputHandler(object sender, DataReceivedEventArgs rec)
{
    // do something with the data
}

Upvotes: 1

Related Questions