I've created a button that starts a "CMD" process and pings a specific machine.
I've got it to Ping successfully, and change the button text back and forth after clicking the button, but I'm not sure how to STOP the ping process (which is a ping -t command) on the second click of the same button.
HERE is my code so far, which selects the button, changes the text on click, starts the process and checks for errors. I've tried to add an "else" statement and say proc.Kill(), but it cant find the proc variable everywhere I try. Is there a correct way to do this?
public void Btn_Ping_Click_1(object sender, EventArgs e)
{
if (Btn_Ping.Text == "Ping")
{
Btn_Ping.Text = "Stop Ping";
}
else if (Btn_Ping.Text == "Stop Ping")
{
Btn_Ping.Text = "Ping";
}
th = new Thread(thread1);
th.Start();
}
public void thread1()
{
if (Btn_Ping.Text == "Stop Ping")
{
try
{
string command = "/c ping " + Txt_Main.Text.Trim() + " -t";
ProcessStartInfo procStartInfo = new ProcessStartInfo("CMD", command);
Process proc = new Process();
proc.StartInfo = procStartInfo;
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardInput = true;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.OutputDataReceived += new DataReceivedEventHandler(proc_OutPutDataRecieved);
proc.Start();
proc.BeginOutputReadLine();
proc.WaitForExit();
}
catch (Exception)
{
//If an error occurs within the try block, it will be handled here
}
}
void proc_OutPutDataRecieved(object sender, DataReceivedEventArgs e)
{
if (e.Data != null)
{
string newLine = e.Data.Trim() + Environment.NewLine;
MethodInvoker append = () => richTextBox1.Text += newLine;
richTextBox1.BeginInvoke(append);
}
}
}