如何保存IShellLibary

时间:2013-07-23 15:03:15

标签: delphi delphi-xe4

以下代码向Libraries添加了一个文件夹,但它没有保存它:

function SHAddFolderPathToLibrary(const plib: IShellLibrary;
  pszFolderPath: LPCWSTR): HResult;
{ Corrected per discussion at StackOverflow }
var
  psiFolder: IShellItem;
begin
  Result := SHCreateItemFromParsingName(pszFolderPath, nil, IID_IShellItem,
    psiFolder);
  if Succeeded(Result) then
  begin
    Result := plib.AddFolder(psiFolder);
  end;
end;

function AddFolderToLibrary(AFolder: string): HRESULT;
{ Add AFolder to Windows 7 library. }
var
  plib: IShellLibrary;
begin
  Result := CoCreateInstance(CLSID_ShellLibrary, nil, CLSCTX_INPROC_SERVER,
    IID_IShellLibrary, plib);
  if SUCCEEDED(Result) then
  begin
    Result := SHAddFolderPathToLibrary(plib, PWideChar(AFolder));
  end;
end;

function RemoveFolderFromLibrary(AFolder: string): HRESULT;
{ Remove AFolder from Windows 7 library. }
var
  plib: IShellLibrary;
begin
  Result := CoCreateInstance(CLSID_ShellLibrary, nil, CLSCTX_INPROC_SERVER,
    IID_IShellLibrary, plib);
  if SUCCEEDED(Result) then
  begin
    Result := SHRemoveFolderPathFromLibrary(plib, PWideChar(AFolder));
  end;
end;

1 个答案:

答案 0 :(得分:3)

您需要致电IShellLibrary.SaveInKnownFolder。像这样:

uses
  Winapi.KnownFolders;

var
  hr: HRESULT;
  plib: IShellLibrary;
  si: IShellItem;
....
// your code to create plib is just fine
hr := plib.SaveInKnownFolder(FOLDERID_Libraries, 'My New Library', 
  LSF_MAKEUNIQUENAME, si);

为了完整起见,这是一个最小的例子:

program W7LibraryDemo;

{$APPTYPE CONSOLE}

uses
  System.SysUtils, 
  System.Win.ComObj, 
  Winapi.KnownFolders, 
  Winapi.ActiveX, 
  Winapi.ShlObj;

procedure Main;
var
  sl: IShellLibrary;
  si: IShellItem;
begin
  OleCheck(CoCreateInstance(CLSID_ShellLibrary, nil, CLSCTX_INPROC_SERVER,
    IID_IShellLibrary, sl));
  OleCheck(sl.SaveInKnownFolder(FOLDERID_Libraries, 'My New Library',
    LSF_MAKEUNIQUENAME, si));
end;

begin
  try
    CoInitialize(nil);
    Main;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.