Rookie programmer
Rookie programmer

Reputation: 25

c# and process to control

I stuck with control logging.

private void btPullLinks_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Run_cmd();
        }

        public void Run_cmd()
        {
            StringBuilder outputBuilder;
            ProcessStartInfo processStartInfo;
            Process process;

            outputBuilder = new StringBuilder();

            processStartInfo = new ProcessStartInfo();
            processStartInfo.CreateNoWindow = true;
            processStartInfo.RedirectStandardOutput = true;
            processStartInfo.RedirectStandardInput = true;
            processStartInfo.UseShellExecute = false;
            processStartInfo.Arguments = @"c:.......py";
            processStartInfo.FileName = @"...../python.exe";

            process = new Process();
            process.StartInfo = processStartInfo;
            process.EnableRaisingEvents = true;
            process.OutputDataReceived += new DataReceivedEventHandler
            (
                delegate (object sender, DataReceivedEventArgs e)
                {
                    outputBuilder.Append(e.Data);
                    txtoutpute.text = e.Data;
                }
            );

            process.Start();
            process.BeginOutputReadLine();
            process.WaitForExit();
            process.CancelOutputRead();

            // use the output
            outputBuilder.ToString();

        }

How to log the output in real time into control ?

My goal is to log the data from delegate function to .Net control.

Tried with solutions offered here. Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on [duplicate]

Upvotes: 0

Views: 342

Answers (1)

Oguz Ozgul
Oguz Ozgul

Reputation: 7187

I don't know why, in an event handler, the runtime throws this exception. Normally, the run-time handles the calling context and executes the event handler routine by the main thread.

https://learn.microsoft.com/en-us/dotnet/framework/winforms/controls/how-to-make-thread-safe-calls-to-windows-forms-controls

But if you can't get rid of it, try (in Program.cs -> Main())

Form.CheckForIllegalCrossThreadCalls = false;

Upvotes: 1

Related Questions