how to kill a process that was started in a thread from the same gui?

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
I have a gui with two simple buttons, start and stop
the start buton launches notepad in a seperate thread using dianostics.process.
I just need the stop button to kill the process.

Here is the notepad class
<pre class="prettyprint using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
namespace open_notepad
{
class Notepad
{


public void Start_run_process(string argument, string filename)
{

ProcessStartInfo StartInfo = new ProcessStartInfo();

StartInfo.UseShellExecute = false;
StartInfo.ErrorDialog = false;
StartInfo.Arguments = argument;
StartInfo.FileName = filename;
StartInfo.RedirectStandardError = true;
StartInfo.RedirectStandardInput = true;
StartInfo.RedirectStandardOutput = true;
StartInfo.CreateNoWindow = true;
Process process = new Process();

process.StartInfo = StartInfo;
try
{
process.Start();
}
catch (Exception ex)
{
string results = ex.ToString();
}
StreamReader reader = process.StandardOutput;


string resulsts = reader.ReadToEnd();

}
public void Process_kill(string filename)
{
Process[] runningProcesses = Process.GetProcessesByName(filename);
foreach (Process process in runningProcesses)
{
process.Kill();
}
}
}
}[/code]
Here is the form
<pre class="prettyprint using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Diagnostics;
namespace open_notepad
{
public partial class Form1 : Form
{
string file_to_open = @"c:templog.txt";
string filename = "notepad.exe";
Notepad notepad = new Notepad();




public Form1()
{
InitializeComponent();

}
public void button1_Click(object sender, EventArgs e)
{

Thread oprocess = new Thread(() => notepad.Start_run_process(file_to_open, filename));
oprocess.Start();
}
private void button2_Click(object sender, EventArgs e)
{
Process[] runningProcesses = Process.GetProcessesByName(filename);
foreach (Process process in runningProcesses)
{
process.Kill();
}

}
}
}[/code]
Im not sure if I should be useing delegates or invoke.
Thanks

View the full article
 
Back
Top