Open Windows Explorer directory, select a specific file (in Delphi)

泪湿孤枕 提交于 2019-12-04 08:30:44

问题


I have a procedure to open a folder in Windows Explorer that gets passed a directory path:

procedure TfrmAbout.ShowFolder(strFolder: string);
begin
   ShellExecute(Application.Handle,PChar('explore'),PChar(strFolder),nil,nil,SW_SHOWNORMAL);
end;

Is there a way to also pass this a file name (either the full file name path or just the name + extension) and have the folder open in Windows Explorer but also be highlighted/selected? The location I am going to has many files and I need to then manipulate that file in Windows.


回答1:


Yes, you can use the /select flag when you call explorer.exe:

ShellExecute(0, nil, 'explorer.exe', '/select,C:\WINDOWS\explorer.exe', nil,
  SW_SHOWNORMAL)

A somewhat more fancy (and perhaps also more reliable) approach (uses ShellAPI, ShlObj):

const
  OFASI_EDIT = $0001;
  OFASI_OPENDESKTOP = $0002;

{$IFDEF UNICODE}
function ILCreateFromPath(pszPath: PChar): PItemIDList stdcall; external shell32
  name 'ILCreateFromPathW';
{$ELSE}
function ILCreateFromPath(pszPath: PChar): PItemIDList stdcall; external shell32
  name 'ILCreateFromPathA';
{$ENDIF}
procedure ILFree(pidl: PItemIDList) stdcall; external shell32;
function SHOpenFolderAndSelectItems(pidlFolder: PItemIDList; cidl: Cardinal;
  apidl: pointer; dwFlags: DWORD): HRESULT; stdcall; external shell32;

function OpenFolderAndSelectFile(const FileName: string): boolean;
var
  IIDL: PItemIDList;
begin
  result := false;
  IIDL := ILCreateFromPath(PChar(FileName));
  if IIDL <> nil then
    try
      result := SHOpenFolderAndSelectItems(IIDL, 0, nil, 0) = S_OK;
    finally
      ILFree(IIDL);
    end;
end;


来源:https://stackoverflow.com/questions/15300999/open-windows-explorer-directory-select-a-specific-file-in-delphi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!