This article provides a guide on how you can create your own version of the Windows task manager. We’ll use WinForms to create a Simple UI and add functionality to view running process and terminate a process.
First create a new WinForms application in .NET framework 4.8 and name it TaskManager.
The UI interface will look like this
Next, from the ToolBox menu, search for DataGridView item
And then drag it unto the MainForm palate.
Next, click on the DataGridView Dropdown options and click on Edit Columns.
Then add three columns that will act as descriptions as follows
Now, to load your form with running processes, navigate to the your Application’s MainForm
By default, your DatatGridView’s name should be dataGridView1
(Unless you previously changed it)
Then, add this piece of code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
LoadProcesses();
}
private void LoadProcesses()
{
dataGridView1.Rows.Clear();
foreach (var proc in System.Diagnostics.Process.GetProcesses())
{
try
{
string status = proc.Responding ? "Running" : "Not Responding";
dataGridView1.Rows.Add(proc.ProcessName, proc.Id, status);
}
catch
{
Console.WriteLine($"Could not access process {proc.ProcessName} with ID {proc.Id}.");
}
}
}
}
When you running your application, you should see all your running processes
Now, lets add a button to each row that will kill that running process
Back on the edit columns section of the DataGridView object, Add a new column like so,
Make sure to set the Type to DataGridViewButtonColumn
to indicate this column will hold a button
Then, add this piece of code to your Form1.cs
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0 && e.ColumnIndex == dataGridView1.Columns["KillProcess"].Index)
{
int pid = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells["PID"].Value);
try
{
var proc = System.Diagnostics.Process.GetProcessById(pid);
proc.Kill();
MessageBox.Show($"{proc.ProcessName} has been terminated.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
LoadProcesses();
}
catch (Exception ex)
{
MessageBox.Show($"Failed to kill process: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
This method will get the particular Process ID
when a particular row is clicked, which is used to call both the Process.GetProcessById
and Kill()
methods.
Don’t forget to wire up your event listener like this
dataGridView1.CellClick += dataGridView1_CellClick;
And that’s it.
If we open up a snipping tool process and then close it from our program, we see that the process was successfully terminated
You can find the full source code of this project here
Happy Coding!!
Top comments (2)
What considerations did you have when choosing WinForms & .NET Framework?
No real considerations, I simply chose both because i’d be working in a windows only environment