Creating a Windows Service with C#, concluded - Creating the Controller
(Page 3 of 4 )
Add a new Windows Application project to the TimeApp solution called “TimeServiceController”. You will see a form named “Form1” now. Change its Text property to “Time Service Controller”, and add the following label and buttons:

Rename them “StatusLabel”, “StartButton”, and “StopButton”. Double-click on the Start button, click back into Design View, and double-click the Stop button. This adds in the click event handlers for our buttons. Now select the “Components” section of the toolbox and double-click “ServiceController”. Change the ServiceName property of the ServiceController to “TimeServerService”. We are done with Design View now; time to switch to Code View.
Now that we have our buttons and service controller wired up, we just need to put a bit of code in the click handlers. Look how simple it is:
private void StartButton_Click(object sender,
System.EventArgs e)
{
this.serviceController1.Start();
this.StatusLabel.Text = this.serviceController1.Status.ToString();
}
private void StopButton_Click(object sender,
System.EventArgs e)
{
this.serviceController1.Stop();
this.StatusLabel.Text = this.serviceController1.Status.ToString();
}
All we have to do now is set up a timer to poll the service status and update the status message in our controller. We will create the timer object in the constructor and call another method to check the status and update our label. The constructor should look like this:
public Form1()
{
InitializeComponent();
System.Timers.Timer t = new System.Timers.Timer(10000);
t.Elapsed += new System.Timers.ElapsedEventHandler
(UpdateStatus);
t.Start();
this.StatusLabel.Text =
this.serviceController1.Status.ToString();
}
The UpdateStatus() method should look like this:
private void UpdateStatus(object sender,
System.Timers.ElapsedEventArgs e)
{
this.StatusLabel.Text = this.serviceController1.Status;
}
Set this class as your startup project and run it for a test drive. See a problem? Even with the timer in place, it seems that our label does not stay quite in sync. To fix this problem, we need to use the Service Controller’s WaitForStatus() method, like this:
private void StartButton_Click(object sender,
System.EventArgs e)
{
this.serviceController1.Start();
this.serviceController1.WaitForStatus(
System.ServiceProcess.ServiceControllerStatus.Running);
this.StatusLabel.Text =
this.serviceController1.Status.ToString();
}
private void StopButton_Click(object sender,
System.EventArgs e)
{
this.serviceController1.Stop();
this.serviceController1.WaitForStatus(
System.ServiceProcess.ServiceControllerStatus.Stopped);
this.StatusLabel.Text =
this.serviceController1.Status.ToString();
}
Next: Using the SysTray Class >>
More C# Articles
More By David Fells