在 Delphi 開發中,若編譯器提示「未定義 IShellItem」,通常是因為缺少必要的頭文件引用。許多開發者嘗試引用 ShellAPI 和 ComObj 仍無法解決,實際上需要引入 ShlObj 單元。
在 uses 子句中加入 ActiveX, ComObj, ShlObj 即可正常使用 IShellItem 及相關 Shell 接口。
uses ActiveX, ComObj, ShlObj;
function TForm1.CopyItem(const aSrcItem, aDest, aNewName: string): HRESULT;
const
CLSID_FileOp: TGUID = '{3ad05575-8857-4850-9277-11b85bdb8e09}';
var
lFileOperation: IFileOperation;
psiFrom, psiTo: IShellItem;
begin
// 初始化 COM 庫為單執行緒單元 (STA)
Result := CoInitializeEx(nil, COINIT_APARTMENTTHREADED or COINIT_DISABLE_OLE1DDE);
if Succeeded(Result) then
begin
// 建立 IFileOperation 介面
Result := CoCreateInstance(CLSID_FileOp, nil, CLSCTX_ALL, IFileOperation, lFileOperation);
if Succeeded(Result) then
begin
// 關閉所有 UI 提示(錯誤、確認、進度對話框)
Result := lFileOperation.SetOperationFlags(FOF_NO_UI);
if Succeeded(Result) then
begin
// 從來源路徑建立 IShellItem
Result := SHCreateItemFromParsingName(aSrcItem, nil, IShellItem, psiFrom);
if Succeeded(Result) then
begin
if aDest <> '' then
begin
// 從目標路徑建立 IShellItem
Result := SHCreateItemFromParsingName(aDest, nil, IShellItem, psiTo);
end;
if Succeeded(Result) then
begin
// 加入複製操作
Result := lFileOperation.CopyItem(psiFrom, psiTo, aNewName, nil);
psiTo := nil;
end;
psiFrom := nil;
end;
if Succeeded(Result) then
begin
// 執行複製操作
Result := lFileOperation.PerformOperations;
end;
end;
// 釋放介面
lFileOperation := nil;
end;
CoUninitialize;
end;
end;
IShellItem、SHCreateItemFromParsingName 等核心介面與函數,是使用 Shell 命名空間物件的前提。SHFileOperation。CoInitializeEx,並在結束時呼叫 CoUninitialize。Succeeded(Result),確保操作鏈路完整。掌握上述要點,即可在 Delphi 7 至較新版本中穩定使用 IShellItem 進行文件/資料夾操作。