Click here to Skip to main content
15,867,308 members
Articles / Programming Languages / C#

ServiceBlocker

Rate me:
Please Sign up or sign in to vote.
5.00/5 (9 votes)
10 Aug 2012CPOL3 min read 22.3K   351   14   8
A Windows service that blocks any unwanted services

Introduction

In this article, I'm going to make a Windows service that reads the name of services which are presented in text file named blacklist, and it's going to block all the services that are in that blacklist txt file. At the end, I'm going to make a GUI for this service so you could easily get rid of any unwanted services that are running on your Windows with just one click .

Making the Service Blocker

First of all, we add a project to our solution and then add a Windows service to it. Add --> New Item --> Windows Service.

The whole thing about our service is that we have an object of timer class named t and a generic list of strings named pl (which stands for ProcessesList) that are global in our service. The timer reads the name of the processes that are in our blacklist text file every 10 milliseconds and adds them to the pl list. Then the service kills all the processes that are in the pl list.

Above everything, we got to write three using statements:

C#
using System.IO;
using System.Diagnostics;
using System.Timers;

So first, I'm going to define our objects:

C#
Timer t = null;
List<string> pl = null;

Now I'm going to override the OnStart method of our service so it will make an instance of the timer and handle its Elapsed method:

C#
protected override void OnStart(string[] args)
{
    if (t == null)
    {
        t = new Timer(10);
        t.Elapsed += new ElapsedEventHandler(t_Elapsed);
    }
    t.Start();
}

void t_Elapsed(object sender, ElapsedEventArgs e)
{
    pl = null;

    StreamReader sr = new StreamReader("E:\\BlackList.txt");
    pl = new List<string>();
    while (sr.Peek()!=-1)
    {
        pl.Add(sr.ReadLine());
    }
    sr.Close();

    foreach (Process p in Process.GetProcesses())
    {
        if (pl.Contains(p.ProcessName))
        {
            p.Kill();
        }
    }
}

The last thing I do is overriding the OnStop method of our service:

C#
protected override void OnStop()
{
  t.Stop();
  pl = null;
}

Now we must build our project once (don't forget add an installer to your service), get the EXE file of our service out of it and then install it with a little help of command prompt. Open command prompt as administrator and use installutil with /i parameter and the path of your service as follows:

C#
installutil /i C:\srvBlock.exe

Tip: You could use /u for uninstalling the service.

Now we've got our service up and running, let's make a GUI for it.

Making the GUI

In our GUI, we have a text box that will let us write the name of the service and add it to the blacklist with the help of add button. The text box also has an autocomplete feature that gets the list of running processes on load.

We also have a listbox that shows us the list of blocked processes. And an erase button that will erase the selected process on the listbox from the black list. We also have a tools menu that can start or end our service or get the status of it.

So this is how our GUI lools like:

330122/GUI.JPG

Before everything, we add a ServiceController to our form and set the ServiceName property of it to our service (I named my ServiceController srvBlock).

Then we write two usings:

C#
using System.IO;
using System.Diagnostics;

In our load event, the first thing we should do is to get the list of running processes and add them to the autocomplete property of our text box. And the second thing is to refresh our service and get the status of it and if it's running, disable our start button and vice versa:

C#
foreach (Process p in Process.GetProcesses())
{
    txtAdd.AutoCompleteCustomSource.Add(p.ProcessName);
}
srvBlock.Refresh();
if (srvBlock.Status.ToString().ToLower() == "running")
    btnStart.Enabled = false;
else btnEnd.Enabled = false;
    RefreshList();

Notince that we have RefreshList() method that refreshes our listbox as follows:

C#
private void RefreshList()
{
    lstProcesses.Items.Clear();
    StreamReader sr = new StreamReader("E:\\BlackList.txt");
    while (sr.Peek() != -1)
    {
        lstProcesses.Items.Add(sr.ReadLine());
    }
    sr.Close();
}

And this how our button works:

C#
private void btnAdd_Click(object sender, EventArgs e)
{
    if (txtAdd.Text != string.Empty)
    {
        if ((MessageBox.Show("Erase all?\nClick no if you want to add to the existing list", 
                "Erase Or Append?", MessageBoxButtons.YesNo)) == DialogResult.Yes)
        {
            StreamWriter sr = new StreamWriter("E:\\BlackList.txt");
            sr.WriteLine(txtAdd.Text, true);
            sr.Close();
        }
        else
        {
            StreamWriter sr = new StreamWriter("E:\\BlackList.txt", true);
            sr.WriteLine(txtAdd.Text, true);
            sr.Close();
        }
        txtAdd.Text = string.Empty;
        RefreshList();
    }
    else
        MessageBox.Show("Textbox is empty!!");
}

Tip: The StreamWriter has an overload that after the file name accepts a bool value and if it's equal to true it would add to the existing file.

And the erase button reads all the name of processes from our file, saves them in a string[] and then sends this array to our Remove() method. The remove methods returns the new string[] with the selected process deleted from it.

C#
private void btnErase_Click(object sender, EventArgs e)
{
    string[] lines = File.ReadAllLines("E:\\BlackList.txt");
    string[] newLines = Remove(lines);
    File.WriteAllLines("E:\\BlackList.txt", newLines);
    RefreshList();
}

private string[] Remove(string[] lines)
{
    int j = lstProcesses.Items.Count;
    string[] newLines = new string[j-1];
    int i = 0;
    foreach (string s in lines)
    {

        if (s != lstProcesses.SelectedItem.ToString())
        {
            newLines[i] = s;
            i++;
        }
    }
    return newLines;
}

Points of Interest

Using this form, you can get rid of any unwanted processes that are messing with your head. I'm sure this code could be written in better ways. I'm open to any new opinion, criticism and so on.

History

  • 13th February, 2012: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) ALFA
Iran (Islamic Republic of) Iran (Islamic Republic of)
loving and living as a programmer

Comments and Discussions

 
QuestionWhy not using ServiceController? Pin
tipsybroom11-Aug-12 10:34
tipsybroom11-Aug-12 10:34 
AnswerRe: Why not using ServiceController? Pin
Ali Javani15-Dec-13 6:56
Ali Javani15-Dec-13 6:56 
Thanks For Your Offer .. i Use that Next Time Wink | ;)

Best Regards
GeneralMy vote of 5 Pin
Patrick Harris10-Aug-12 15:08
Patrick Harris10-Aug-12 15:08 
GeneralRe: My vote of 5 Pin
Ali Javani15-Dec-13 6:57
Ali Javani15-Dec-13 6:57 
GeneralMy vote of 5 Pin
mohammad_davati5-Mar-12 0:36
mohammad_davati5-Mar-12 0:36 
GeneralMy vote of 5 Pin
Ashkan.hosseini18-Feb-12 7:04
Ashkan.hosseini18-Feb-12 7:04 
GeneralRe: My vote of 5 Pin
Ali Javani15-Dec-13 7:00
Ali Javani15-Dec-13 7:00 
GeneralMy vote of 5 Pin
WebMaster14-Feb-12 20:31
WebMaster14-Feb-12 20:31 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.