Gman88
Gman88

Reputation: 3

Programming the same button to open and close an EXE file

Im trying to program one single button to open and close an exe file, so when I press it once, it opens the file, when I press it again then it closes the file.

Im able to program the button to open the file but i cannot get it to close.

private void button1_click(object sender, EventArgs e)
{

Process proc = new Process();
proc.StartInfo.FileName = @"C:\Program Files (x86)\TeamViewer\TeamViwer.exe";
proc.Start();
}

Upvotes: 0

Views: 424

Answers (1)

nalnpir
nalnpir

Reputation: 1193

You can set up a boolean flag, whenever you open your program you set that flag to true, whenever you close it, you set it to false. If its true then it tries to kill the process, the other way around it just executes the code you got there.

bool running = false;
private void button1_click(object sender, EventArgs e)
{
    if (running)
    {
        var processes = Process.GetProcesses();

        foreach (Process pr in processes)
        {

            if (pr.ProcessName == "TeamViwer")
            {
                pr.Kill();
            }

        }
       running = false;
    }
    else
    {
        Process proc = new Process();
        proc.StartInfo.FileName = @"C:\Program Files (x86)\TeamViewer\TeamViwer.exe";
        proc.Start();
        running = true;
    }
}

Upvotes: 1

Related Questions