我想在C#中的Windows服务中收听设备通知。我将RegisterDeviceNotification与RegisterServiceCtrlHandlerEx一起使用。它是来自互联网的标准代码,但它不起作用。
可能是什么问题?
代码示例:
try
{
_handler = new ServiceControlHandlerEx(ServiceControlHandler);
IntPtr handle2 = RegisterServiceCtrlHandlerEx(this.serviceName, _handler, IntPtr.Zero);
if (handle2 == IntPtr.Zero)
return false;
DEV_BROADCAST_DEVICEINTERFACE deviceInterface = new DEV_BROADCAST_DEVICEINTERFACE();
int size = Marshal.SizeOf(deviceInterface);
deviceInterface.dbcc_size = size;
deviceInterface.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
IntPtr bufferDeviceInterface = default(IntPtr);
bufferDeviceInterface = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(deviceInterface, bufferDeviceInterface, true);
_deviceHandle = RegisterDeviceNotification(handle2, bufferDeviceInterface,
DEVICE_NOTIFY_SERVICE_HANDLE | DEVICE_NOTIFY_ALL_INTERFACE_CLASSES);
if (_deviceHandle == IntPtr.Zero)
return false;
return true;
}
catch (Exception ex)
{
return false;
}
答案 0 :(得分:0)
在发布的代码示例中无法看到,但不能在单独的线程中调用RegisterServiceCtrlHandlerEx和RegisterDeviceNotification。必须在“主线程”中调用这些方法,即重写ServiceBase.OnStart()的方法。