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
Mattias Sj?gren - 15 Sep 2003 20:46 GMT
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

Signature
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/
Please reply only to the newsgroup.
Miki Kalishov - 16 Sep 2003 09:47 GMT
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?
> Miki,
>
[quoted text clipped - 11 lines]
>
> Mattias