Moving files and directories to the recycle bin with Delphi

uses SysUtils, ShellApi;

  ////////////////////////////////////////////////////////////////
  // - "Filenames" is a list of files and directories you want to delete.
  //   the user will be asked for confirmation and the progress dialog will
  //   be displayed if necessary.
  // - "ParentWindow" is the parent window for message boxes, you can pass "0".
  // after executing, you have to check, which files where really deleted,
  // because the user can cancel the deleting procedure.
procedure Sto_DeleteFiles(const ParentWindow: HWND;
  const Filenames: TStrings; const ToRecycleBin: Boolean = true);
var
  iFile: Integer;
  sFilenames: string;
  myFileOp: SHFILEOPSTRUCT;
begin
  if (Filenames.Count = 0) then
    Exit;
  // create a #0 delimited string with two trailing #0
  sFilenames := '';
  for iFile := 0 to Filenames.Count - 1 do
    sFilenames := sFilenames + ExcludeTrailingPathDelimiter(Filenames.Strings[iFile])
      + #0;
  sFilenames := sFilenames + #0;
  // prepare the SHFILEOPSTRUCT
  FillChar(myFileOp, SizeOf(myFileOp), 0);
  myFileOp.Wnd := ParentWindow;
  myFileOp.wFunc := FO_DELETE;
  myFileOp.pFrom := PChar(sFilenames);
  // could be moved to the recyclebin, even if "ToRecycleBin" is false.
  if ToRecycleBin then
    myFileOp.fFlags := myFileOp.fFlags or FOF_ALLOWUNDO;
  SHFileOperation(myFileOp);
end;

No comments:

Post a Comment