手頭的程式需要修改註冊表, 以讓當前程式成為某格式的預設開啟程式並關聯表徵圖; Vista 之後需要管理 員許可權才能操作註冊表, 很麻煩, 所以有了下面的嘗試.
unit Unit1;interfaceuses 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, 要開啟的檔案的尾碼是 .tstend;end.