C# Process is killing program not cancel
<p>I have problem with process stopping.</p>

<p>I tried one code but its killing programm not stopping process.</p>

<p>Program <a href="http://i.stack.imgur.com/qQabB.png" rel="nofollow">Form Design</a></p>

<p>Example:</p>

<p>I try to ping 127.0.0.1 and its starting infinite ping ( -t ) and i need to stop process, but its just killing it. </p>

<p>If i click "Stop!" then program stops and closed.</p>

<p>My code:</p>

<pre><code>namespace PingProgramm
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        Thread th;
        private void button1_Click(object sender, EventArgs e)
        {
            th = new Thread(thread1);
            th.Start();
        }

        public void thread1()
        {
            try
            {
                string command = "/c ping -t " + textBox1.Text;
                ProcessStartInfo procStartInfo = new ProcessStartInfo("CMD", command);
                Process proc = new Process();
                proc.StartInfo = procStartInfo;
                procStartInfo.RedirectStandardOutput = true;
                procStartInfo.RedirectStandardInput = true;
                procStartInfo.RedirectStandardError = true;
                procStartInfo.UseShellExecute = false;
                procStartInfo.CreateNoWindow = true;
                proc.OutputDataReceived += new DataReceivedEventHandler(proc_OutputDataReceived);
                proc.Start();
                proc.BeginOutputReadLine();
                proc.WaitForExit();
            }
            catch (Exception)
            {
                //if an error occurs with in the try block, it will handled here.
            }
        }
        void proc_OutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            if (stop)
            {
                // sender is our process instance
                // so we can cast that safely here
                var proc = (Process)sender;
                // brutally kill it
                proc.Pause();
                // or more gently, send a ctrl+C
                // http://stackoverflow.com/a/285041/578411
                proc.StandardInput.Pause();
            }
            if (e.Data != null)
            {
                string newLine = e.Data.Trim() + Environment.NewLine;
                MethodInvoker append = () =&gt; richTextBox1.Text += newLine;
                richTextBox1.BeginInvoke(append);
            }
        }
        bool firstTime = true;
        private void textBox1_Click(object sender, EventArgs e)
        {
            if (firstTime)
            {
                firstTime = false;
                textBox1.Clear();
            }
        }

        bool stop = false;
        private void button2_Click(object sender, EventArgs e)
        {
            stop = true;
        }
    }
}
</code></pre>

<p>Best wishes,</p>

<p>KLDesigns</p>