手頭的程序需要修改注冊表, 以讓當前程序成為某格式的默認打開程序並關聯圖標; 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.