Mega Code Archive

 
Categories / Delphi / Examples
 

Com and windows services

A little tip on using COM with Windows Services. Today I tried accessing an XML document from a Windows service. When I prototyped my classes using a Windows forms app everything worked fine, but when I used the same classes in a Windows service I kept getting the error "CoInitialize has not been called". CoInitialize must be called for every thread when using any kind of COM object. The catch is that the TService class which comes with Delphi creates its own support thread in order to execute the OnExecute event. Once you know this, is it quite simple to rectify your code procedure TMyService.ServiceExecute(Sender: TService);begin CoInitialize(nil); try //Your code here finally CoUnInitialize; end;end;