Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Run process and then kill it using a button

I hope that you can help me with this one, my C# is very rusty.

I'm running an executable when the form loads.

    private void Form1_Load(object sender, EventArgs e)
    {
        ProcessStartInfo exe = new ProcessStartInfo();
        exe.Arguments = "arguments";
        exe.FileName = "file.exe";
        Process.Start(exe);
    }

And I would like to kill that process using a button, but I don't know how to achieve that.

    private void button1_Click(object sender, EventArgs e)
    {

    }

Thanks.

like image 300
user2077474 Avatar asked May 08 '26 02:05

user2077474


1 Answers

Process.Start returns an object of type Process. You can save it into variable, then use the method Kill, which Immediately stops the associated process (msdn)

For example declare a field at Form1 level:

class Form1
{
    private Process process;

    private void Form1_Load(object sender, EventArgs e)
    {
        //running notepad as an example
        process = Process.Start("notepad"); 
    }

    //and then at button handler kill that process
    private void button1_Click(object sender, EventArgs e)
    {
        //consider adding check for null
        process.Kill();
    }
}
like image 109
Ilya Ivanov Avatar answered May 09 '26 16:05

Ilya Ivanov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!