在delphi 7中使用IFileOperation

roz*_*za 0 delphi api

我想用IFileOperation CopyItem一个文件从一个目录复制到另一个目录在delphi 7中有一个简单的例子吗?

The*_*Fox 7

我找到了MSDN文档,它包含了一个示例.以下是转换为Delphi的示例:

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: IShellItem;
  psiTo: IShellItem;
begin
  //
  // Initialize COM as STA.
  //
  Result := CoInitializeEx(nil, COINIT_APARTMENTTHREADED or COINIT_DISABLE_OLE1DDE);
  if Succeeded(Result) then
  begin

    //
    // Create the IFileOperation interface
    //
    Result := CoCreateInstance(CLSID_FileOp, nil, CLSCTX_ALL, IFileOperation,
                          lFileOperation);
    if Succeeded(Result) then
    begin
      //
      // Set the operation flags. Turn off all UI from being shown to the
      // user during the operation. This includes error, confirmation,
      // and progress dialogs.
      //
      Result := lFileOperation.SetOperationFlags(FOF_NO_UI);
      if Succeeded(Result) then
      begin
        //
        // Create an IShellItem from the supplied source path.
        //
        Result := SHCreateItemFromParsingName(aSrcItem,
                                         nil,
                                         IShellItem, psiFrom);
        if Succeeded(Result) then
        begin
          if aDest <> '' then
          begin
            //
            // Create an IShellItem from the supplied
            // destination path.
            //
            Result := SHCreateItemFromParsingName(aDest,
                                             nil,
                                             IShellItem, psiTo);
          end;

          if Succeeded(Result) then
          begin
            //
            // Add the operation
            //
            Result := lFileOperation.CopyItem(psiFrom, psiTo, aNewName, nil);

            psiTo := nil;
          end;

          psiFrom := nil;
        end;

        if Succeeded(Result) then
        begin
          //
          // Perform the operation to copy the file.
          //
          Result := lFileOperation.PerformOperations;
        end;
      end;

      //
      // Release the IFileOperation interface.
      //
      lFileOperation := nil;
    end;

    CoUninitialize;
  end;
end;
Run Code Online (Sandbox Code Playgroud)

免责声明: IFileOperation.CopyItem可从Windows Vista及更高版本获得.所以上面的例子只适用于Delphi 2010(和2009?).由于我在Delphi 7上,因此我无法编译,因为我缺少单元ShlObj的最新版本.Fortunatly使用Delphi中的COM非常容易,因此转换示例并不是什么大问题.我用Google搜索了IFileOperation的CLSID,所以我不知道它是不是正确的.

如果您真的希望这与Delphi 7一起使用,则必须定义IFileOperation.Jeroen提供的链接具有IShellItem的定义,但不适用于IFileOperation.如果您认识某人使用Delphi 2010版本,您可以向他询问ShlObj.pas(但它受版权保护,因此您必须自己翻译Shobjidl.h或等待其他人这样做,您可以查看JEDI项目).

当所有这些看起来非常复杂时,请尝试Windows Api调用CopyFile.