Kill external process when closing form [closed]

0

I created a form that executes an external program when I click on a button load program, but when I close the form I wanted it to give it a kill process in the task manager.

But he says he has access denied when I close the form, it seems that he even tries to kill the process but it does not work.

Inside Form1_FormClosing looks like this:

Process[] myProcesses;
myProcesses = Process.GetProcessesByName("meu programa");
foreach (Process myProcess in myProcesses)
{
    if (myProcess.CloseMainWindow())
        myProcess.Close();

    if (!myProcess.HasExited)
        myProcess.Kill();
}
    
asked by anonymous 13.10.2016 / 22:45

1 answer

1

Hello, Please try to store the external program process in a variable at the moment it is started, so that you are sure that when you close the form you are closing the program you started.

In the example below, in the buttonLoadProgram_MouseUp method the external program is started using System.Diagnostics.Process and this process is stored in the MyProcess global variable. In the Form1_FormClosing method the process stored in the MyProcess global variable is terminated inside a Try ... catch where you can better analyze the error you are trying to overcome.

Follow the complete code, and then tell us what happened:)

using System;
using System.Diagnostics;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
  public partial class Form1 : Form
  {

    /// <summary>
    /// Variavel para guardar o processo.
    /// </summary>
    public Process MyProcess;

    /// <summary>
    /// Contrutor
    /// </summary>
    public Form1()
    {
        InitializeComponent();
    }

    /// <summary>
    /// Inicia o programa externo
    /// </summary>
    private void buttonLoadProgram_MouseUp
        (object sender, MouseEventArgs e)
    {

        MyProcess = new Process();
        //Caminho do programa
        MyProcess.StartInfo.
            FileName = @"C:\Program Files (x86)\Notepad++\notepad++.exe";

        MyProcess.Start();
        MyProcess.EnableRaisingEvents = true;

    }

    /// <summary>
    /// Ao fechar o form o programa externo tb é fechado.
    /// </summary>
    private void Form1_FormClosing
        (object sender, FormClosingEventArgs e)
    {
        try
        {
            //Finalizando programa
            MyProcess.Kill();
        }
        catch (Exception exception)
        {
            //Observe o erro e tente nos contar mais sobre o ocorrido
            MessageBox.Show(exception.Message);
        }
    }
}

}

    
14.10.2016 / 07:17