15.02.2015 Views

C# 4 and .NET 4

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

688 ❘ ChaPTer 25 windOws services<br />

}<br />

}<br />

return controller.Status == ServiceControllerStatus.Running;<br />

public bool EnablePause<br />

{<br />

get<br />

{<br />

return controller.Status == ServiceControllerStatus.Running &&<br />

controller.CanPauseAndContinue;<br />

}<br />

}<br />

public bool EnableContinue<br />

{<br />

get<br />

{<br />

return controller.Status == ServiceControllerStatus.Paused;<br />

}<br />

}<br />

}<br />

In the ServiceControlWindow class, the method RefreshServiceList() gets all the services using<br />

ServiceController.GetServices() for display in the list box. The GetServices() method returns<br />

an array of ServiceController instances representing all Windows Services installed on the operating<br />

system. The ServiceController class also has the static method GetDevices() that returns a<br />

ServiceController array representing all device drivers. The returned array is sorted with the help of<br />

the generic Array.Sort() method. The sort is done by the DisplayName as is defined with the Lambda<br />

expression that is passed to the Sort() method. Using Array.ConvertAll(), the ServiceController<br />

instances are converted to the type ServiceControllerInfo. Here, a Lambda expression is passed<br />

that invokes the ServiceControllerInfo constructor for every ServiceController object. Last, the<br />

ServiceControllerInfo array is assigned to the DataContext property of the window for<br />

data binding:<br />

protected void RefreshServiceList()<br />

{<br />

ServiceController[] services = ServiceController.GetServices();<br />

Array.Sort(services, (s1, s2) =><br />

s1.DisplayName.CompareTo(s2.DisplayName));<br />

}<br />

this.DataContext =<br />

Array.ConvertAll(services, controller =><br />

new ServicesControllerInfo(controller));<br />

code snippet ServiceControl/ServiceControlWindow.xaml.cs<br />

The method RefreshServiceList() to get all the services in the list box is called within the constructor<br />

of the class ServiceControlWindow. The constructor also defines the event h<strong>and</strong>ler for the Click event of<br />

the buttons:<br />

public ServiceControlWindow()<br />

{<br />

InitializeComponent();<br />

}<br />

RefreshServiceList();<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!