2009. október 27., kedd

Determining the associated application


Problem/Question/Abstract:

How can I get the application associated with a document?

Answer:

Where is that information?

The applications associated with the file extensions are stored in the Windows Registry. To get this information first we should retrieve the "class" that a file extensions belongs to. This information can be found at:

  HKEY_CLASSES_ROOT\.ext\(default)

where ".ext" is the file extension you want (like ".txt", ".bmp", etc.). Then we get the command line used to open that kind of files. To do that, we retrieve the data under

  HKEY_CLASSES_ROOT\class\Shell\Open\Command\(default)

where "class" is the file class an extension belongs to. That string usually has the form

  "D:\PATH\APPNAME.EXT" "%1" -OPTIONS

where %1 is a placeholder for the document file to open with the application, so we should find its position within the string and replace it with the filename we want to open.

Example

The following function returns the command line of the associated application to open a documente file:

function GetAssociation(const DocFileName: string): string;
var
  FileClass: string;
  Reg: TRegistry;
begin
  Result := '';
  Reg := TRegistry.Create(KEY_EXECUTE);
  Reg.RootKey := HKEY_CLASSES_ROOT;
  FileClass := '';
  if Reg.OpenKeyReadOnly(ExtractFileExt(DocFileName)) then
  begin
    FileClass := Reg.ReadString('');
    Reg.CloseKey;
  end;
  if FileClass <> '' then
  begin
    if Reg.OpenKeyReadOnly(FileClass + '\Shell\Open\Command') then
    begin
      Result := Reg.ReadString('');
      Reg.CloseKey;
    end;
  end;
  Reg.Free;
end;

Copyright (c) 2001 Ernesto De Spirito
Visit: http://www.latiumsoftware.com/delphi-newsletter.php

Nincsenek megjegyzések:

Megjegyzés küldése