提供一個可直接使用的 Delphi 函式 SetAssociatedExec,將指定副檔名註冊為自訂檔案類型、設定檔案描述、MIME 類型、開啟命令與預設圖示。函式回傳 Boolean 表示成功與否。
function TFm_main.SetAssociatedExec(FileExt, FileType, FileDescription,
MIMEType, ExecName: String): Boolean;
var
Reg: TRegistry;
ShFileInfo: TSHFILEINFO;
IconIndex: Integer;
begin
Result := False;
// 參數檢查:副檔名與執行檔路徑不可為空,副檔名必須含前導點 (如 .BMP)
if (FileExt = '') or (ExecName = '') then Exit;
Reg := TRegistry.Create;
try
Reg.RootKey := HKEY_CLASSES_ROOT;
// 1. 建立/開啟副檔名鍵值,設定預設值為檔案類型名稱
if not Reg.OpenKey(FileExt, True) then Exit;
Reg.WriteString('', FileType);
if MIMEType <> '' then
Reg.WriteString('Content Type', MIMEType);
Reg.CloseKey;
// 2. 建立/開啟檔案類型鍵值,設定描述
if not Reg.OpenKey(FileType, True) then Exit;
Reg.WriteString('', FileDescription);
Reg.CloseKey;
// 3. 設定開啟命令:shell\open\command
if not Reg.OpenKey(FileType + '\shell\open\command', True) then Exit;
// %1 代表被雙擊的檔案完整路徑
Reg.WriteString('', ExecName + ' "%1"');
Reg.CloseKey;
// 4. 設定預設圖示:DefaultIcon
if not Reg.OpenKey(FileType + '\DefaultIcon', True) then Exit;
// 格式:執行檔路徑,圖示資源索引 (0 為第一個圖示)
Reg.WriteString('', ExecName + ',1');
Reg.CloseKey;
Result := True;
finally
Reg.Free;
end;
end;
// 將 .mydoc 關聯給 MyEditor.exe
SetAssociatedExec('.mydoc', 'MyEditor.Document', '我的文件',
'application/x-mydoc', 'C:\MyApp\MyEditor.exe');
| 步驟 | 登錄表路徑 | 用途 |
|---|---|---|
| 1 | HKEY_CLASSES_ROOT\.ext | 副檔名映射到檔案類型 (ProgID) |
| 2 | HKEY_CLASSES_ROOT\FileType | 檔案類型描述 |
| 3 | HKEY_CLASSES_ROOT\FileType\shell\open\command | 雙擊執行命令,%1 為檔案路徑 |
| 4 | HKEY_CLASSES_ROOT\FileType\DefaultIcon | 檔案圖示,格式 exe路徑,索引 |
HKEY_CLASSES_ROOT (Vista+ 需 UAC 提權)。SHGetFileInfo 可動態取得系統圖示索引,程式碼中保留註解供參考。SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, nil, nil) 通知殼層重新整理圖示。