2006. augusztus 20., vasárnap

Determine if a COM object is registered


Problem/Question/Abstract:

At startup I need to determine if a COM server has been registered. If not, I will call RegisterComServer. Now I am calling RegisterComServer every time the application starts, which I do not think is a good idea. Is there a proper way to test for it being registered?

Answer:

You can try several methods:

a) Use CLSIDFromProgID method:

{ ... }
var
  strOLE: string;
begin
  strOLE = "YourCOMServer.Application"; {your ProgID}
  if (CLSIDFromProgID(PWideChar(WideString(strOLE), ClassID) = S_OK) then
    begin
      { ... }
    end;
end;

b) Check the registry:

{ ... }
const
  cKEY = '\SOFTWARE\Classes\CLSID\%s\InprocServer32';
var
  sKey: string;
  sComServer: string;
  exists: boolean;
  Reg: TRegistry;
begin
  Reg := TRegistry.Create;
  try
    Reg.RootKey := HKEY_LOCAL_MACHINE;
    sKey := format(cKEY, [GuidToString(ClassID)]);
    if Reg.OpenKey(sKey, False) then
    begin
      sComServer := Reg.ReadString('');
      if FileExists(sComServer) then
      begin
        { ... }
      end;
    end;
  finally
    Reg.free;
  end;
end;

Nincsenek megjegyzések:

Megjegyzés küldése