0

I have created an interactive shell on C# but I don't know how to access my forms control and assign received values to my textbox, I know that the threads can't access the UI thread but in this case, I don't seem to be able to fix the problem, there is going to be many input and output in that shell, and I want to make sure that everything is shown to user.

 public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Process process = new Process();
            process.StartInfo.FileName = "echoo.exe";
            process.StartInfo.Arguments = "";
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError = true;


            process.ErrorDataReceived += new DataReceivedEventHandler(OutputHandler);

            process.StartInfo.RedirectStandardInput = true;

            process.Start();

            StreamWriter sw = process.StandardInput;

            process.BeginOutputReadLine();
            process.BeginErrorReadLine();

            sw.WriteLine("sent");
            process.WaitForExit();

        }
        static void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
        {

            Form1.textBox1.Text = outLine.Data;
        }


    }
Erik A
  • 31,639
  • 12
  • 42
  • 67
primee
  • 80
  • 2
  • 12

1 Answers1

1

If you write this in your setter:

static void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
    if(textBox1.InvokeRequired)
    {
        textBox1.BeginInvoke((MethodInvoker) delegate() {textBox1.Text = outLine.Data;});    
    }
    else
    {
        textBox1.Text = outLine.Data;
    }
}

It'll force the set onto the UI thread. I found this from this question: stack question

Dan Rayson
  • 1,315
  • 1
  • 14
  • 37
  • error: An object reference is required for the nonstatic field, method, or property 'Form1.textBox1' – primee May 19 '18 at 11:26
  • Oh haha, you're already in the Form1 class.Just remove the `Form1.` from the textbox variables. Updated answer. – Dan Rayson May 19 '18 at 11:28
  • the same error occurred again, this time i removed static and `process.WaitForExit();` as this preventing ui to process assigning i guess and it works now, thank you. – primee May 19 '18 at 14:47