Pages

Thursday, 15 May 2014

How to Start and Kill a Process in C#



Hi, 

Here you are gonna learn to Start and Kill a Process in C#. Suppose if you want to open / close an application such as Notepad, Calculator etc with C# codes, this tutorial will be helpful. 

Let's start;



Steps

1. Open Visual Studio and Create a New Project -> Windows Form Application with
    Name StartKillProcess
.

2. Now add 2 buttons to your empty form and design it as shown in the below screenshot.
    Also change the button names to;

     Name         Text
     btnStart     Start Notepad
     btnStop      Stop Notepad

3. Now double click on Start Notepad button and copy the below code; 
    
    //to open notepad, for calculator give "calc"
    System.Diagnostics.Process.Start("Notepad");

4. Also double click on Stop Notepad button and copy the below code;

       Process[] processes = null;
      processes = Process.GetProcessesByName("Notepad");
      foreach (Process process in processes)
      {
            process.Kill();
      }

5. The full source code is shown below;
      
    Form1.cs

using System;
using System.Diagnostics;
using System.Windows.Forms;

namespace StartKillProcess
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("Notepad");
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            Process[] processes = null;
            processes = Process.GetProcessesByName("Notepad");
            foreach (Process process in processes)
            {
                process.Kill();
            }
        }
    }
}

6. Now Run the project and click on Start Notepad button to open Notepad and click on
   Stop Notepad button to close the Notepad.
   
   Output


Conclusion
  • You have learned to Start and Kill a Process in C#. If you have any doubts or errors please comment it.

See Also


1 comment:

 

About Me

I am Tijo Tom, a Computer Engineer from India.Right from my schooling, I had a passion for Programming, PC Tricks, Virus Creation and Hacking.

I started this blog on Jan 1, 2014 to share my views and ideas with the world.

You can know more about me on