C# windows service and RegisterServiceCtrlHandlerEx

  • Thread starter Thread starter Miki Kalishov
  • Start date Start date
M

Miki Kalishov

Hi all,

I have a C# windows service that need to handle the
SERVICE_CONTROL_DEVICEEVENT event.
This event is not supported by the ServiceBase class so I tried to use the
P/Invoke to call RegisterServiceCtrlHandlerEx() and register the call back
method HandlerEx() but i was unable to receive valid handle.
my code is listed below any help on the subject would be appreciated


public class Service1 : System.ServiceProcess.ServiceBase
{
private delegate int callbackEx(int control,int eventType,IntPtr
eventData,IntPtr context);
[DllImport("kernel32.dll", SetLastError=true)]
static extern unsafe int GetLastError();
[DllImport("advapi32.dll", SetLastError=true)]
static extern unsafe IntPtr RegisterServiceCtrlHandlerEx(string
lpServiceName,callbackEx cbex,IntPtr context);

private System.ComponentModel.Container components = null;

public static int callbackexfunc(int control,int eventType,IntPtr
eventData,IntPtr context)
{
return 0;
}

public Service1()
{
InitializeComponent();
callbackEx myCallback = new callbackEx(Service1.callbackexfunc);
IntPtr h =
RegisterServiceCtrlHandlerEx(this.ServiceName,myCallback,IntPtr.Zero );
MessageBox.Show(GetLastError().ToString());

}
......
}


Thanks
Miki
 
Miki,
callbackEx myCallback = new callbackEx(Service1.callbackexfunc);
IntPtr h =
RegisterServiceCtrlHandlerEx(this.ServiceName,myCallback,IntPtr.Zero );

The callback will fail when the myCallback delegate gets garbage
collected at some point in the future. To prevent that, you should
keep a reference to the delegate in a class field.

MessageBox.Show(GetLastError().ToString());

Use Marshal.GetLastWin32Error() instead of GetLastError().



Mattias
 
Thanks for replay,
I've done what you suggested but my call to RegisterServiceCtrlHandlerEx
still fails,
it return 0 which is invalid handle and the Marshal.GetLastWin32Error()
return 0xc0000005
any idea why this happens?
 
Back
Top