We can use the ServiceController component to Start/Stop a service from an application without having to open the services panel. This can be used in Admin / Dashboard applications which needs to monitor and manage a set of services in a server. The ServiceController is part of the “ System.ServiceProcess” assembly and has methods to start/stop or perform other operations on a Windows Service. In this post we shall see on how to use the ServiceController to manage the state of our Windows Service “NotificationServices”
1. Create a new Windows Forms Application Project
2. In the form designer, drag a ServiceController component.
3. Rename the ServiceController accordingly.
4. I have named it as NotificationServiceController.
5. The ServiceName property of the ServiceController should be set to the service which it is supposed to manage.
6. In my case I will use the controller to manage the NotificationService, hence I will set the property to “NotificationService”
7. Add 4 buttons Start, Stop, Pause, Continue to manage the service and appropriate labels to display the status of the service.
8. In the Load event of the form, add code to Enable/Disable the buttons based on the status of the NotificationService, also set the current state of the service in the label.
private void fromServiceTester_Load(object sender, EventArgs
e)
{
SetServiceState();
}
//
private void
SetServiceState()
{
// Enable or Diable the Buttons based on the status of the
Service.
btnStart.Enabled = NotificationServiceController.Status == ServiceControllerStatus.Stopped;
btnStop.Enabled = NotificationServiceController.Status != ServiceControllerStatus.Stopped;
btnPause.Enabled = NotificationServiceController.Status == ServiceControllerStatus.Running;
btnContinue.Enabled = NotificationServiceController.Status == ServiceControllerStatus.Paused;
//
// Set the current state of the Service.
lblCurrentState.Text = NotificationServiceController.Status.ToString();
}
9. Add code to the click event of all the buttons to Manage the service.
private void
btnStart_Click(object sender, EventArgs e)
{
NotificationServiceController.Start();
NotificationServiceController.WaitForStatus(ServiceControllerStatus.Running);
SetServiceState();
}
//
private void
btnStop_Click(object sender, EventArgs e)
{
NotificationServiceController.Stop();
NotificationServiceController.WaitForStatus(ServiceControllerStatus.Stopped);
SetServiceState();
}
//
private void
btnPause_Click(object sender, EventArgs e)
{
NotificationServiceController.Pause();
NotificationServiceController.WaitForStatus(ServiceControllerStatus.Paused);
SetServiceState();
}
//
private void
btnContinue_Click(object sender, EventArgs e)
{
NotificationServiceController.Start();
NotificationServiceController.WaitForStatus(ServiceControllerStatus.Running);
SetServiceState();
}
10. Build and run the application, click on the buttons and notice that the status of the service changes appropriately in the services panel.
No comments:
Post a Comment