View Single Post
 
Old 05-14-2019, 10:01 PM
FreakaZoid2 FreakaZoid2 is offline
Senior Member
 
Join Date: Jul 2009
Posts: 334
Default Thread not able to access a function method defined in program

i have my thread logic working and doing what i want it to do except when it tries to call this function(CopyFileIFileOperationForceDirectories) it does nothing. presumably failing. just not sure why. i have another function defined (CopyFiles) that does work within the thread.


Code:
function CopyFileIFileOperationForceDirectories(const srcFile, destFile : string) : boolean;
var
  r : HRESULT;
  fileOp: IFileOperation;
  siSrcFile: IShellItem;
  siDestFolder: IShellItem;
  destFileFolder, destFileName : string;
  pbc : IBindCtx;
  w32fd : TWin32FindData;
  ifs : TFileSystemBindData;
begin
  result := false;

  destFileFolder := ExtractFileDir(destFile);
  destFileName := ExtractFileName(destFile);

  //init com
  r := CoInitializeEx(nil, COINIT_APARTMENTTHREADED or COINIT_DISABLE_OLE1DDE);
  if Succeeded(r) then
  begin
    //create IFileOperation interface
    r := CoCreateInstance(CLSID_FileOperation, nil, CLSCTX_ALL, IFileOperation, fileOp);
    if Succeeded(r) then
    begin
      //set operations flags
      r := fileOp.SetOperationFlags(FOF_NOCONFIRMATION OR FOFX_NOMINIMIZEBOX);
      if Succeeded(r) then
      begin
        //get source shell item
        r := SHCreateItemFromParsingName(PChar(srcFile), nil, IShellItem, siSrcFile);
        if Succeeded(r) then
        begin
          //create binding context to pretend there is a folder there
          if NOT DirectoryExists(destFileFolder) then
          begin
            ZeroMemory(@w32fd, Sizeof(TWin32FindData));
            w32fd.dwFileAttributes := FILE_ATTRIBUTE_DIRECTORY;
            ifs := TFileSystemBindData.Create;
            ifs.SetFindData(w32fd);
            r := CreateBindCtx(0, pbc);
            r := pbc.RegisterObjectParam(STR_FILE_SYS_BIND_DATA, ifs);
          end
          else
            pbc := nil;

          //get destination folder shell item
          r := SHCreateItemFromParsingName(PChar(destFileFolder), pbc, IShellItem, siDestFolder);

          //add copy operation
          if Succeeded(r) then r := fileOp.CopyItem(siSrcFile, siDestFolder, PChar(destFileName), nil);
        end;

        //execute
        if Succeeded(r) then r := fileOp.PerformOperations;

        result := Succeeded(r);

        OleCheck(r);
      end;
    end;

    CoUninitialize;
  end;
end;


function CopyFiles(From, Dest: string): boolean;
var
  F     : TShFileOpStruct;
begin
  Result := true;
  FillChar(F, Sizeof(F), 0);
  From := From + #0;
  Dest := Dest + #0;
  with F do
  begin
    Wnd := Application.MainForm.Handle;
    wFunc := FO_COPY;
    pFrom := pChar(From);
    pTo := pChar(Dest);
    fFlags := FOF_SIMPLEPROGRESS or FOF_NOCONFIRMATION or FOF_NOCONFIRMMKDIR;
    lpszProgressTitle := PWideChar(WideString(Dest));
  end;
  if ShFileOperation(F) <> 0 then
    Result := false;
end;