手头的程序需要修改注册表, 以让当前程序成为某格式的默认打开程序并关联图标; Vista 之后需要管理员权限才能操作注册表, 很麻烦, 所以有了下面的尝试.

unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;

type
  TForm1 = class(TForm)
    Memo1: TMemo;
    Button1: TButton;
    procedure FormCreate(Sender: TObject);
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

uses System.IOUtils, Winapi.ShellAPI, Winapi.ShlObj; //RegApp 函数用到的单元

//关联默认程序的函数
procedure RegApp(const aExt, aAppName, aAppPath: string);
const
  nRegFmt = 'Windows Registry Editor Version 5.00'        + sLineBreak +
            '[HKEY_CLASSES_ROOT\%0:s]'                    + sLineBreak +
            '@="%1:s"'                                    + sLineBreak +
            '[HKEY_CLASSES_ROOT\%1:s\DefaultIcon]'        + sLineBreak +
            '@="%2:s,0"'                                  + sLineBreak +
            '[HKEY_CLASSES_ROOT\%1:s\shell]'              + sLineBreak +
            '[HKEY_CLASSES_ROOT\%1:s\shell\open]'         + sLineBreak +
            '[HKEY_CLASSES_ROOT\%1:s\shell\open\command]' + sLineBreak +
            '@="%3:s"';
var
  RegStr: string;
  str3, str4: string;
  RegTmpFile: string;
begin
  str3 := aAppPath.Replace('\', '\\');
  str4 := Format('"%s" "%%1"', [str3]).Replace('"', '\"');
  RegStr := Format(nRegFmt, [aExt, aAppName, str3, str4]);
  RegTmpFile := TPath.GetTempPath + 'RegTmp.reg';
  with TStringList.Create do begin
    Text := RegStr;
    SaveToFile(RegTmpFile);
    Free;
  end;
  ShellExecute(0, nil, PChar(RegTmpFile), nil, nil, SW_SHOWNORMAL);
  SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, nil, nil); //刷新图标显示
end;


procedure TForm1.FormCreate(Sender: TObject);
var
  S: string;
begin
  S := ParamStr(1);
  if FileExists(S) then Memo1.Lines.LoadFromFile(S);
end;

//执行注册函数; 执行后, 可随便修改一个文本文件的后缀为 tst, 然后双击测试
procedure TForm1.Button1Click(Sender: TObject);
begin
  RegApp('.tst', 'MyApp1', Application.ExeName); //假定程序名称是 MyApp1, 要打开的文件的后缀是 .tst
end;

end.

posted on 2013-07-10 14:33  万一  阅读(2494)  评论(2编辑  收藏  举报