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);
}
}
}
}