Starting and stopping services in VB.NET

Capt_Ron

Active member
Joined
Apr 29, 2005
Messages
39
Programming Experience
1-3
I would like to be able to start and stop a service using VB.NET. I need to check if a service is running and launch another app if it is, if it's not then start the service first. When the user closes the app, I want to stop the service.

I've been looking in Help, but it's a little convoluted.

Thanks for your direction.
Ron

PS: This message is cross posted to General.
 
You should use a ServiceController component. Set the ServiceName property to bind to the desired service and use the Status property to determine whether it is running. Use the Start and Stop methods to do the obvious. You can use WaitForStatus to wait until the service has started before launching the additional app, which you would do using the Process.Start method. I'm not sure whether you mean you want the service stopped when your original app closes or the additional app you started. If it's your original, simply call Stop on the ServiceController in the Closed (or Closing, if the object has been disposed by the time of the Closed event) event handler of your main form. If you mean the additional app, you can call WaitForExit on the Process if you don't mind your original app freezing. Otherwise you would need to do periodical checks, controlled by a Timer, to see whether the Process was still running and, if not, stop the service. If the user closes your main app first, I doubt that there would be a way for you to stop the service.
 
Back
Top