How to Control a Windows Service from Code

How to control a Windows Service from C# .NET

Introduction

This simple example shows how you can control a Windows Service from C# code. In this example, we are going to do the following tasks on the spooler (print) service:

  • Check if it is disabled
  • Check if it is enabled
  • Stop the service
  • Start the service
The .NET Framework is already equipped with a class called ServiceController to control Windows services. With this class, you can start, stop, pause, restart and get the status from a Windows Service.

Since it is not possible to check if a Windows Service is enabled or disabled with the ServiceController class and to wrap everything up, I created a class with all the code inside. This class is called Windo wsServiceMonitor. The class is extended with a few functions

like:

  • Disable (to disable the Windows Service)
  • Enable (to enable the Windows Service
  • IsDisabled (to check if the Windows Service is disabled)
To get these 3 functions to work, we use the ManagementObjectSearcher and the Registry class.

Using the Code

To test the WindowsServiceMonitor class, we create a simple Winform application as shown below:

From this form, we use the WindowsServiceMonitor class. Before we can use this class, we need to create it. In the form application, this is done in the Form load event.

To start the spooler, we call the Start() function:

To stop the spooler, we call the Stop() function:

To disable the spooler, we call the Disable() function:

To enable the spooler, we call the Enable() function:

All this is done through our WindowsServiceMonitor class:

Source: www.codeproject.com

Category: Forex

Similar articles: