今天使用SelectDirectory选择文件夹,用SHFileOperation来删除文件夹,一直都报错,蛋疼了老半天,原来是SelectDirectory之后就将当前目标设为SelectDirectory选择的目录了,所以删除时就会报“文件夹正在使用,不能删除”,最后用在调用SelectDirectory之后,再用SetCurrentDir将当前目录设为“C:\”就Ok了。
procedure TForm1.DeleteDirectoryTree(AHandle: THandle; const ADelDir: string);
var
SHFileOpStruct: TSHFileOpStruct;
DelDir: PChar;
DirLen: Integer;
begin
DirLen := Length(ADelDir) + 2;
GetMem(DelDir, DirLen);
try
FillChar(DelDir^, DirLen, #0);
StrCopy(DelDir, PChar(ADelDir));
with SHFileOpStruct do
begin
Wnd := AHandle;
wFunc := FO_DELETE;
pFrom := DelDir;
pTo := nil;
fFlags := FOF_ALLOWUNDO;
fAnyOperationsAborted := False;
hNameMappings := nil;
lpszProgressTitle := nil;
if SHFileOperation(SHFileOpStruct) <> 0 then
RaiseLastWin32Error;
end;
finally
FreeMem(DelDir, DirLen);
end;
end;
function TForm1.GetDirectory: string;
var
CurDir: string;
begin
CurDir := 'C:\';
// if call SelectDirectory, then set current directory is result
// so if don't set current directory, can not delete the folder
if not SelectDirectory(Result, [], 0) then
Result := EmptyStr;
SetCurrentDir(CurDir);
end;