C#:运行进程然后使用按钮终止它

use*_*474 2 c# executable kill

我希望你可以帮助我这个,我的C#非常生疏.

我在表单加载时运行可执行文件.

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

我想用一个按钮来杀死那个过程,但我不知道如何实现这个目标.

    private void button1_Click(object sender, EventArgs e)
    {

    }
Run Code Online (Sandbox Code Playgroud)

谢谢.

Ily*_*nov 5

Process.Start返回一个类型的对象Process.你可以将它保存到变量中,然后使用方法Kill,其中Immediately stops the associated process(msdn)

例如,在Form1级别声明一个字段:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)