Register a File Command for a Windows Shell Menu from Delphi code

Most of the file types (files "grouped" by their extension) in Windows have an associated application which gets executed when a user double clicks a file in the Windows Explorer.


As expected, you can programmatically associate a file type with your Delphi program. For example, if your application is producing ".ADP" files, you can specify that your application is executed when a user doble clicks a ".ADP" file.

Sometimes, you will need to add (register) a custom command for a known file type. For example, you may want an option to open PAS files (Delphi units) with Notepad.

Here are the two functions you can use to register or unregister a command for a file type (extension).

uses Registry;

function RegisterFileTypeCommand(fileExtension, menuItemText, target: string) : boolean;
var
  reg: TRegistry;
  fileType: string;
begin
  result := false;
  reg := TRegistry.Create;
  with reg do
  try
    RootKey := HKEY_CLASSES_ROOT;
    if OpenKey('.' + fileExtension, True) then
    begin
      fileType := ReadString('') ;
      if fileType = '' then
      begin
        fileType := fileExtension + 'file';
        WriteString('', fileType) ;
      end;
      CloseKey;
      if OpenKey(fileType + '\shell\' + menuItemText + '\command', True) then
      begin
        WriteString('', target + ' "%1"') ;
        CloseKey;
        result := true;
      end;
    end;
  finally
    Free;
  end;
end;

function UnRegisterFileTypeCommand(fileExtension, menuItemText: string) : boolean;
var
  reg: TRegistry;
  fileType: string;
begin
  result := false;
  reg := TRegistry.Create;
  with reg do
  try
    RootKey := HKEY_CLASSES_ROOT;
    if OpenKey('.' + fileExtension, True) then
    begin
      fileType := ReadString('') ;
      CloseKey;
    end;
    if OpenKey(fileType + '\shell', True) then
    begin
      DeleteKey(menuItemText) ;
      CloseKey;
      result := true;
    end;
  finally
    Free;
  end;
end;
Here's an example of usage.

The first call to "RegisterFileTypeCommand" adds the "Preview in Notepad" menu item to the system shell menu. If you right-click any PAS file, you will see the "Preview in Notepad" in the system shell menu.

Once you no longer need this command, you can remove it using the provided "UnRegisterFileTypeCommand" function.

//Register ... use
RegisterFileTypeCommand('pas','Preview in Notepad','C:\WINDOWS\Notepad.exe') ;

//Unregister
UnRegisterFileTypeCommand('pas','Preview in Notepad') ;


posted @ 2006-12-19 10:15  hingman  阅读(346)  评论(0)    收藏  举报