Categories
NETCF

Windows CE Services and Compact Framework

Neither .NETCF v1.0 or v2.0 will support runtime hosting, this means it’s not possible to write a service in managed code which will run within the Services.exe process. However it is often useful to be able to query and manipulate other system services from managed code.


An example of this is where a system service needs to be stopped so that you can access some hardware – such as the OBEX listener service on Windows Mobile which opens the Infrared port. With this scenario in mind I set about wrapping some of the CE functionality for managing services, using the desktop framework as a model.


The resultant library – InTheHand.ServiceProcess.dll is designed as a subset of System.ServiceProcess.dll – this is the assembly which is added as a reference to your project when you create a windows service project with the desktop framework. The library includes a single class ServiceController which is created with the identifier of the service you which to attach to. Under Windows CE these services have an identifier in the form of a device name e.g. AAAN: where AAA is the prefix, often providing a clue as to the purpose of the service, and N is a numerical index. Returning to our example of OBEX the service is called OBX0:. If you don’t know the name of a particular service you can either trawl through the registry under HKLMServices, or better still call the ServiceController.GetServices static method. The final consideration is to ensure you close/dispose the ServiceController when you have finished working with it. Our OBEX shutdown code looks like this:-


ServiceController scObex = new ServiceController(“OBX0:”);
scObex.Stop();

while(scObex.Status!=ServiceControllerStatus.Stopped)
{
    System.Threading.Thread.Sleep(1000);
}

scObex.Close();


Notice that the WaitForStatus method isn’t supported so in this case we periodically check the status while sleeping. If we weren’t bothered when the service shutdown you could leave out this section, even when you call Close() to close our handle to the service it will continue with it’s action and shutdown in it’s  own time.


In terms of platform support, this services.exe model is supported on CE.NET 4.x and above so this includes Windows Mobile 2003 and above.


You can download the library here:-


http://www.inthehand.com/Services.aspx

By Peter Foot

Microsoft Windows Development MVP