{-------------------------------------------------------------------------------
过程名: ShGetFiles
作者: Kingron
日期: 2004.03.26
参数:
Files: TStrings;
Folder: string;
SubDir: Boolean
Files: 存储返回的文件名列表
Folder: 需要获取的文件名的目录
SubDir: 是否包含子目录下的文件
返回值: 无
说明: 利用Shell获取文件名列表
-------------------------------------------------------------------------------}
function GetPIDLFromPath(const Path: string): PItemIDList;
{ 返回指定Path对应的PItemIDList,在调用SH函数的时候经常用到PItemIDList哦 }
var
IDesktopFolder: IShellFolder;
Dummy: Cardinal;
begin
SHGetDesktopFolder(IDesktopFolder);
IDesktopFolder.ParseDisplayName(GetActiveWindow, nil, POleStr(WideString(Path)), Dummy, Result, Dummy);
end;
function GetPathFromPIDL(Pid: PItemIDList): string;
{ 根据PItemIDList返回指定的Path }
begin
SetLengthEx(Result, 1024);
ShGetPathFromIDList(PID, PChar(Result));
end;
function IsFolder(ShellFolder: IShellFolder; ID: PItemIDList): Boolean;
{ 判断ID是否是一个文件夹,是,返回True }
var
Flags: UINT;
begin
Flags := SFGAO_FOLDER;
ShellFolder.GetAttributesOf(1, ID, Flags);
Result := SFGAO_FOLDER and Flags <> 0;
end;
procedure ShGetFiles(Files: TStrings; Folder: string; SubDir: Boolean);
{-------------------------------------------------------------------------------
过程名: ShGetFiles
作者: Kingron
日期: 2004.03.26
参数: Files: TStrings;
Folder: string;
SubDir: Boolean
Files: 存储返回的文件名列表
Folder: 需要获取的文件名的目录
SubDir: 是否包含子目录下的文件
返回值: 无
说明: 利用Shell获取文件名列表
-------------------------------------------------------------------------------}
var
PID: PItemIDList;
Desktop, ChildFolder: IShellFolder;
EnumIDList: IEnumIDList;
Dummy, Fetched: DWORD;
Buffer: array[0..1024] of char;
begin
/// 获取桌面的Shell对象
SHGetDesktopFolder(Desktop);
/// 获取指定目录的PID
PID := GetPIDLFromPath(Folder);
/// 绑定ShellFolder和PID,返回绑定后的ShellFolder对象
Desktop.BindToObject(PID, nil, IID_IShellFolder, ChildFolder);
if not Assigned(ChildFolder) then
begin
FreePIDL(PID);
Exit;
end;
/// 扫描所有的对象
if Succeeded(ChildFolder.EnumObjects(GetActiveWindow, SHCONTF_INCLUDEHIDDEN or SHCONTF_NONFOLDERS or SHCONTF_FOLDERS, EnumIDList)) then
while EnumIDList.Next(1, PID, Fetched) = S_OK do /// 枚举所有的PID
begin
if IsFolder(ChildFolder, PID) then
begin /// 如果是目录
if SubDir then
ShGetFiles(Files, IncludeTrailingPathDelimiter(Folder) + GetDisplayName(ChildFolder, PID, False), SubDir);
end
else
Files.Add(IncludeTrailingPathDelimiter(Folder) + GetDisplayName(ChildFolder, PID, False));
CoTaskMemFree(PID); // Remember to free PIDLs!
end;
FreePidl(PID);
end;