Search code examples
topshelf

How to hook the service control handler from a Topshelf service


I have an existing Windows service that uses Topshelf very successfully.

I now need to have the service receive notifications when specific USB devices are connected / disconnected to / from the machine.

I can't see anything in Topshelf that would allow me to do this. But I believe that there is a way to do it using Win32 APIs like ServiceControlHandlerEx and RegisterDeviceNotification with the DEVICE_NOTIFY_SERVICE_HANDLE option.

Will using these Win32 APIs interfere with Topshelf? As I understand it, Topshelf wraps the service control handler itself so my service also trying to do the same thing may cause it some problems?

Update: It is possible to hook device notifications from the service control handler within a Topshelf based service. See sample project for details. Many thanks to Chris Patterson for his help.


Solution

  • Topshelf won't interfere with you calling these Win32 APIs.