index > Visual C# General > Redirect Standard Input

Redirect Standard Input

Hi,
I am a newbie to C# and Im trying to redirect standard input and output of a console program written in C (MS VC 6.0) to a textbox on a form. The code for the redirecting looks like this:

private System.IO.StreamWriter c_StreamInput = null;
private System.IO.StreamReader c_StreamOutput = null;
private Thread c_ThreadRead = null;
private Process c_Process = null;

private void ReadStdOutputThreadProc()
{
while(!c_Process.HasExited)
{
try
{
string str = c_StreamOutput.ReadLine();
while (str != null)
{
c_StreamOutput.BaseStream.Flush();
txtboxCNF.AppendText(str + "\r\n");
Thread.Sleep(100);
str = c_StreamOutput.ReadLine();
}
}
catch (Exception) { }
}
}

private void btnCNF_Click(object sender, System.EventArgs e)
{
if(c_Process == null)
{
c_Process = new Process();
ProcessStartInfo psi = new ProcessStartInfo("console.exe");
psi.UseShellExecute = false;
psi.RedirectStandardOutput = true;
psi.RedirectStandardInput = true;
psi.CreateNoWindow = true;
c_Process.StartInfo = psi;
c_Process.Start();

c_StreamInput = c_Process.StandardInput;
c_StreamOutput = c_Process.StandardOutput;

c_StreamInput.AutoFlush = true;

c_ThreadRead = new Thread(new ThreadStart(ReadStdOutputThreadProc));
c_ThreadRead.IsBackground = true;
c_ThreadRead.Start();
}
}

private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (c_ThreadRead != null)
{
c_ThreadRead.Abort();
c_ThreadRead.Join();
}
if(c_Process != null && !c_Process.HasExited)
c_Process.Kill();
}

private void txtboxCNF_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if(e.KeyValue == 13)
{
c_StreamInput.WriteLine((char)e.KeyValue+"\0\n");
}
}

The console application that I am trying to run (console.exe) is a simple C program that prints a line text and then calls the gets() function. The code is basically this:

#include "stdafx.h"
#include <conio.h>
#include <string.h>

void create_it();

int main(int argc, char* argv[])
{
create_it();

return 1;
}

void create_it()
{
char str_nodes[256], str_filename[256], str_username[256], str_serial[256];

printf("Welcome to the console program\n");

/* Display maximum number of nodes */
printf ("Max Nodes : ");
gets( str_nodes);

/* get file name */
printf ("Enter user configuration file name : ");
gets (str_filename);

/* get user name */
printf ("User Name : ");
gets (str_username);

/* get serial number */
printf ("Serial Id : ");
gets (str_serial);
}

The problem is that I am not able to use the console app interactively using the text box on the form. Is there any way I can get it to work so that what I type into the textbox goes into the console app as its standard input?

Thanks in advance for your help.




Dribble
Dribble

Hi!

I don't know if that's the problem, but your txtboxCNF_KeyDown method seems rather strange. You check for the character code 13, and then write the same code plus some bogus 0 character to the stream.

c_StreamInput.WriteLine((char)e.KeyValue+"\0\n");

This would essential write "\n\0\n" to the stream everytime someone presses the enter key. I think you should have here something like:

c_StreamInput.WriteLine ( textboxCNF.Text );

So you write whatever is in your textbox at that moment, and not the current key pressed(which would be enter). You do not need to include the line feed for WriteLine method. You also might want to clear the textbox after writing its contents to the stream, so a new line of input can be added.

Another problem might come from the fact that you modify the contents of controls from another thread. It is not always a good idea to directly access the controls that were created on the UI thread from the working thread. Consider using the Invoke method that is available for your Form (actually inherited from Control).

Hope this helps!

Lenard

LenardG
You need to buffer all the key's and send them in one long input when you receive a carrage return, here is a little example:


private StringBuilder _inputBuffer = new StringBuilder();

private void txtboxCNF_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if(e.KeyValue == 13)
{
_inputBuffer.Append( e.KeyValue );
_inputBuffer.Append( '\0' );
_inputBuffer.Append( '\n' );

String input = _inputBuffer.ToString();
c_StreamInput.WriteLine( input );

_inputBuffer.Clear();
}
else
{
_inputBuffer.Append( e.KeyValue );
}
}





** Microsoft Community Moderator ** http://born2code.net **
PJ. van de Sande

I have tried your suggestion, but it doesn't seem to help. My code now looks like this (if that helps):

private void ReadStdOutputThreadProc()

{

while(!c_Process.HasExited)

{

try

{

string str = c_StreamOutput.ReadLine();

while (str != null)

{

c_StreamOutput.BaseStream.Flush();

txtboxCNF.AppendText(str + "\r\n");

Thread.Sleep(100);

str = c_StreamOutput.ReadLine();

}

}

catch (Exception) { }

}

}

private void CNFOutputHandler(object sendingProcess, DataReceivedEventArgs outLine)

{

// Collect the sort command output.

if (!String.IsNullOrEmpty(outLine.Data))

{

txtboxCNF.AppendText(outLine.Data + "\r\n");

}

}

private void btnCNF_Click(object sender, System.EventArgs e)

{

if(c_Process == null)

{

c_Process = new Process();

ProcessStartInfo psi = new ProcessStartInfo("C:\\XPDistribution\\console.exe");

psi.UseShellExecute = false;

psi.RedirectStandardOutput = true;

//c_Process.OutputDataReceived += new DataReceivedEventHandler(CNFOutputHandler);

psi.RedirectStandardInput = true;

psi.CreateNoWindow = true;

c_Process.StartInfo = psi;

c_Process.Start();

c_StreamInput = c_Process.StandardInput;

c_StreamOutput = c_Process.StandardOutput;

c_StreamInput.AutoFlush = true;

c_ThreadRead = new Thread(new ThreadStart(ReadStdOutputThreadProc));

c_ThreadRead.IsBackground = true;

c_ThreadRead.Start();

//c_Process.BeginOutputReadLine();

}

}

private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)

{

if (c_ThreadRead != null)

{

c_ThreadRead.Abort();

c_ThreadRead.Join();

}

if(c_Process != null && !c_Process.HasExited)

c_Process.Kill();

}

private void txtboxCNF_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)

{

if (e.KeyValue == 13)

{

_inputBuffer.Append(e.KeyValue);

_inputBuffer.Append('\0');

_inputBuffer.Append('\n');

String input = _inputBuffer.ToString();

c_StreamInput.WriteLine(input);

_inputBuffer.Remove(0, _inputBuffer.Length);

}

else

{

_inputBuffer.Append(e.KeyValue);

}

}

Thanks for all your time.




Dribble
Dribble
reply 4

You can use google to search for other answers

 

More Articles

• How do I delete multiple files (Code Request)?
• IS Word Control exists ?
• help with string match regex
• Adding Objects to ArrayList using Button_Click
• How to write to Excel file?
• FTP
• Custom File Properties
• Use of unassigned local variable
• How to get html file from a specific url location?
• Inmediate window functionality for C#
Bookmark and Share
Welcome to Bokebb   New Update  
 

New Articles

• 2 combobox columns in datagridview
• Center picturebox in Panel with AutoScroll
• NET 2.0 and SetROP2
• Problem with slow screen update
• Don;t want to show the seconds value for
• Regular Expression needed
• Changing the Browsable attribute dynamic
• Setting CommandButton's BackColor progra
• best obfuscator
• Creating a new Object w/ a Button Click
• Refresh Desktop
• Populating a form with dynamically creat
• Sytem Monitoring
• Server controls (textbox) does not work
• FILE* type in C#

Hot Articles

• How to change the calendar of DateTimePi
• general question C#...
• help needed in creating runtime objects
• Editor
• Using Outlook to send Messages in a LAN
• Not executing some event
• Change CurrentUICulture
• ECC design pattern using Generics
• how to remove this black selected thing?
• C# .Net 2005 codepage 862 to 28598
• static methods
• SendMessage to Date Time Picker Control
• C# & vb2005e
• simple parse problem
• Making It Fullscreen

Recommend Articles

• combobox and WebService dataSet
• How to make palettes in C#[Windows] whic
• Immediate window: how to pass literal ar
• XML
• updating dataset
• Buttons/TextBox/Integers
• DataGridView EditingControlShowing Cells
• <E2ETraceEvent> when using XMLWrit
• Pass variables to form2 forom form1 usin
• How can I solve this connection error ?
• Embedding an application written in C# i
• webforms?
• C# string split: How to split this string?
• Please give an advice in the following c
• RichTextBox