nikorio
nikorio

Reputation: 691

How to stop Process.Start process for python code from c#

In C# application I have running of python console application exe file with process by environment variable path:

private void button1_Click(object sender, EventArgs e)
{
    var filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "folder\\python.exe");   
    Process.Start(filePath); 
}

and I want stop this process and close console with button click or any other condition, not sure what I'm doing wrong:

private void button2_Click(object sender, EventArgs e)
{
    var filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "folder\\python.exe");
    var process = Process.Start(filePath);
    process.Kill();
}

Upvotes: 1

Views: 1518

Answers (1)

Alex
Alex

Reputation: 191

In the second button click, you are starting a new process (and killing it immediately) instead of stopping the process you started with the first button click. To stop the process that was started from the first button click, you will need to store the Process object that was created in a variable, and then call the Kill() method on that object when the second button is clicked.

This is a very simple example (Note that each time button1 is pressed, it would assign the newly created process to the runningProcess variable)

public class FormClass
{
    Process runningProcess;

    public FormClass()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        var filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "folder\\python.exe");   
        runningProcess = Process.Start(filePath); 
    }

    private void button2_Click(object sender, EventArgs e)
    {
        if(!runningProcess.HasExited)
        {
            runningProcess.Kill();
        }
    }
}

Upvotes: 1

Related Questions