I built this simple form to illustrate my issue:
What I need:
- Execute a script that I have in python (built an .exe from pyinstaller) clicking on "button1"
- Update the progress bar and the label with the percentage the python script prints out as soon as it prints.
What I've got:
- The code works fine, does what I need, but not as soon as the script print the percentage.
Here's my code:
private static double value= 0;
private void button1_Click(object sender, EventArgs e)
{
Process process = new Process();
process.StartInfo.FileName = @"C:\Users\User\Desktop\testeProgresso.exe";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.OutputDataReceived += new DataReceivedEventHandler((_sender, _e) =>
{
// Prepend line numbers to each line of the output.
if (!String.IsNullOrEmpty(_e.Data))
{
value= double.Parse(_e.Data);
}
});
process.Start();
process.BeginOutputReadLine();
process.WaitForExit();
label1.Text += value.ToString();
progressBar1.Value = (int)value;
process.WaitForExit();
process.Close();
}
I need it does so when the process is finished, I'll close this form and open another.
EDIT:
private void button6_Click(object sender, EventArgs e)
{
Process process = new Process();
process.StartInfo.FileName = @"C:\Users\User\Desktop\testeProgresso.exe";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.SynchronizingObject = this;
process.EnableRaisingEvents = true;
process.Exited += (s, evt) => { process?.Dispose();};
process.OutputDataReceived += new DataReceivedEventHandler((_sender, _e) =>
{
if (!String.IsNullOrEmpty(_e.Data))
{
value = double.Parse(_e.Data);
label1.Text += value.ToString();
progressBar1.Value = (int)value;
}
});
process.Start();
process.BeginOutputReadLine();
//process.Close();
}
as Jimi suggested, I made some changes. But it still just updates the whole thing after the process is done.
Plus, I couldnt implement the Exited
event, because I dont know how.