Whenever you need to start, stop, pause, or pass parameters to a Windows service, Visual Studio .NET's ServiceController component makes it easy.
In order to use ServiceController, you first need to add the component to your Windows application, expand the Toolbox, and choose ServiceController. Once you add it to your form, it will appear on the bottom of the window. Click the object (which is ServiceController1 by default) and update the component's properties.
In general, the ServiceController component is very useful for sending the commands to a Windows service on a particular machine. So, for my example, I will try to start and stop a service on the local machine called WebClient. I will set the ServiceName property of the ServiceController1 to WebClient.
To stop the WebClient service on the local machine, add the following code:
To start the WebClient service on the local machine, add the following code:
To verify that the code is behaving as expected, open Services under the Microsoft Management Console either by going to Control Panel | Administrative Tools | Services or Start | Run and typing Services.msc. Locate the service you are trying to start and stop (in our example, it's WebClient). After running the code above and refreshing the Services view, you should confirm that the service has responded to the command.
The ServiceController component also allows you to access services on different machines by specifying the MachineName property. Visit MSDN for details about using the ServiceController.MachineName Property.
Irina Medvinskaya has been involved in technology since 1996. She has an MBA from Pace University and works as a project manager at Citigroup.
————————————————————————————————————————————Get Visual Basic tips in your inbox
Advance your scripting skills to the next level with TechRepublic's free Visual Basic newsletter, delivered each Friday. Automatically subscribe today!