Bill
Bill

Reputation: 3033

How To Save a IShellLibary

The following code adds a folder to Libaries, but it does not save it:

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;

Upvotes: 3

Views: 166

Answers (1)

David Heffernan
David Heffernan

Reputation: 612993

You need to call IShellLibrary.SaveInKnownFolder. Like this:

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);

For the sake of completeness, here is a minimal example:

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.

Upvotes: 3

Related Questions