Kill external process when close form

Asked

Viewed 771 times

0

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

However he says he has access denied when I close the form, it seems that he even tries to kill process no longer works.

Within the Form1_FormClosing was like this:

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

    if (!myProcess.HasExited)
        myProcess.Kill();
}

1 answer

1

Hello, If you’d be so kind... Try to store the external program process in a variable at the time it is started, so you can be sure that at the time of closing 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 global Myprocess variable. In the Form1_formclosing method the process stored in the global variable Myprocess is finished inside a Try...catch where you can better analyze the error you are trying to overcome.

Follow the full 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);
        }
    }
}

}

  • Adriano Silva Ribeiro, Thanks for your help, but your code is already identical to mine, the error when I close the form and it tries to close or program is the following msg:

  • Access to the 'C: Windows System32 Sistemab.exe' path has been denied

Browser other questions tagged

You are not signed in. Login or sign up in order to post.