마음의 안정을 찾기 위하여 - [Delphi] Check if windows explorer already opened on given path
2660154
629
969
관리자새글쓰기
태그위치로그방명록
별일없다의 생각
dawnsea's me2day/2010
색상(RGB)코드 추출기(Color...
Connection Generator/2010
최승호PD, '4대강 거짓말 검...
Green Monkey**/2010
Syng의 생각
syng's me2DAY/2010
천재 작곡가 윤일상이 기획,...
엘븐킹's Digital Factory/2010
[Delphi] Check if windows explorer already opened on given path
Delphi/파일 컨트롤 | 2025/10/01 11:23

ShellWindows enumeration

The following code was inspired by this article and this example. Here is a scheme:

1. IShellWindows.Item(n)
2. ⤷ IDispatch.QueryInterface(IWebBrowserApp)
3.   ⤷ IWebBrowserApp.QueryInterface(IServiceProvider)
4.     ⤷ IServiceProvider.QueryService(STopLevelBrowser, IShellBrowser)
5.       ⤷ IShellBrowser.QueryActiveShellView
6.         ⤷ IShellView.QueryInterface(IFolderView)
7.           ⤷ IFolderView.GetFolder(IPersistFolder2)
8.             ⤷ IPersistFolder2.GetCurFolder
9.               ⤷ ITEMIDLIST

And some description:

  1. As first you obtain the IShellWindows interface reference and iterate its items.

  2. For each item, the IShellWindows interface returns window's IDispatch interface which you then query for an IWebBrowserApp interface reference.

  3. The obtained IWebBrowserApp interface (for documentation refer to IWebBrowser2, as it's their implementation) provides except others also the information about the host window, like handle which can be later used for bringing the window to foreground. We need to go deeper though. So let's query this interface reference for the IServiceProvider interface (which is an accessor for getting interfaces for the given service).

  4. Now from the top-most browser implementation service query its IShellBrowser interface. A reference of this interface is still not interesting for our aim.

  5. The obtained IShellBrowser query for the displayed Shell view object.

  6. Now we can finally say, if the iterated Shell window is not an Internet Explorer window. So far they were having common interfaces implemented. Now if we query the obtained IShellView for the IFolderView interface and it succeeds, it is not Internet Explorer and we can continue.

  7. Query the obtained IFolderView reference for the IPersistFolder2 interface for the currently displayed folder object.

  8. If we succeeded even there and we got IPersistFolder2 reference, let's get the ITEMIDLIST for the current folder object.

  9. And if we succeeded even with this last step, we have ITEMIDLIST of the currently displayed folder of a Windows Explorer instance (or the same interface implementor) and we can finally check if the obtained ITEMIDLIST equals to the one we parsed for the input path. If so, bring that window to foreground, if not, continue to the next iteration.




uses
  ActiveX, ShlObj, SHDocVw, ComObj;
{ because of Win32Check }
{$WARN SYMBOL_PLATFORM OFF}
const
  IID_IFolderView: TGUID = '{CDE725B0-CCC9-4519-917E-325D72FAB4CE}';
  IID_IPersistFolder2: TGUID = '{1AC3D9F0-175C-11D1-95BE-00609797EA4F}';
  IID_IServiceProvider: TGUID = '{6D5140C1-7436-11CE-8034-00AA006009FA}';
  SID_STopLevelBrowser: TGUID = '{4C96BE40-915C-11CF-99D3-00AA004AE837}';
type
  IFolderView = interface(IUnknown)
  ['{CDE725B0-CCC9-4519-917E-325D72FAB4CE}']
    function GetCurrentViewMode(out pViewMode: UINT): HRESULT; stdcall;
    function SetCurrentViewMode(ViewMode: UINT): HRESULT; stdcall;
    function GetFolder(const riid: TIID; out ppv): HRESULT; stdcall;
    function Item(iItemIndex: Integer; out ppidl: PItemIDList): HRESULT; stdcall;
    function ItemCount(uFlags: UINT; out pcItems: Integer): HRESULT; stdcall;
    function Items(uFlags: UINT; const riid: TIID; out ppv): HRESULT; stdcall;
    function GetSelectionMarkedItem(out piItem: Integer): HRESULT; stdcall;
    function GetFocusedItem(out piItem: Integer): HRESULT; stdcall;
    function GetItemPosition(pidl: PItemIDList; out ppt: TPoint): HRESULT; stdcall;
    function GetSpacing(var ppt: TPoint): HRESULT; stdcall;
    function GetDefaultSpacing(out ppt: TPoint): HRESULT; stdcall;
    function GetAutoArrange: HRESULT; stdcall;
    function SelectItem(iItem: Integer; dwFlags: DWORD): HRESULT; stdcall;
    function SelectAndPositionItems(cidl: UINT; var apidl: PItemIDList; var apt: TPoint; dwFlags: DWORD): HRESULT; stdcall;
  end;
  EShObjectNotFolder = class(Exception);
function ILGetSize(pidl: PItemIDList): UINT; stdcall;
  external 'shell32.dll' name 'ILGetSize';
function ILIsEqual(pidl1: PItemIDList; pidl2: PItemIDList): BOOL; stdcall;
  external 'shell32.dll' name 'ILIsEqual';
function InitVariantFromBuffer(pv: Pointer; cb: UINT; out pvar: OleVariant): HRESULT; stdcall;
  external 'propsys.dll' name 'InitVariantFromBuffer';
function CoAllowSetForegroundWindow(pUnk: IUnknown; lpvReserved: Pointer): HRESULT; stdcall;
  external 'ole32.dll' name 'CoAllowSetForegroundWindow';
resourcestring
  rsObjectNotFolder = 'Object "%s" is not a folder.';
{ this parses the input folder path and creates ITEMIDLIST structure if the given
  folder path is a valid absolute path to an existing folder }
function GetFolderIDList(const Folder: string): PItemIDList;
const
  SFGAO_STREAM = $00400000;
var
  Count: ULONG;
  Attributes: ULONG;
  ShellFolder: IShellFolder;
begin
  OleCheck(SHGetDesktopFolder(ShellFolder));
  Attributes := SFGAO_FOLDER or SFGAO_STREAM;
  OleCheck(ShellFolder.ParseDisplayName(0, nil, PWideChar(WideString(Folder)), Count, Result, Attributes));
  if not ((Attributes and SFGAO_FOLDER = SFGAO_FOLDER) and (Attributes and SFGAO_STREAM <> SFGAO_STREAM)) then
  begin
    CoTaskMemFree(Result);
    raise EShObjectNotFolder.CreateFmt(rsObjectNotFolder, [Folder]);
  end;
end;
{ translated from the link mentioned in this comment; D2009 does not allow me to
  create an OleVariant of type VT_ARRAY|VT_UI1 which is needed for the Navigate2
  method so I've imported and used the InitVariantFromBuffer function here
  https://msdn.microsoft.com/en-us/library/windows/desktop/gg314982(v=vs.85).aspx }
procedure OpenNewExplorer(IDList: PItemIDList);
var
  Location: OleVariant;
  WebBrowser: IWebBrowser2;
begin
  OleCheck(CoCreateInstance(CLASS_ShellBrowserWindow, nil, CLSCTX_LOCAL_SERVER, IID_IWebBrowser2, WebBrowser));
  OleCheck(CoAllowSetForegroundWindow(WebBrowser, nil));
  OleCheck(InitVariantFromBuffer(IDList, ILGetSize(IDList), Location));
  try
    WebBrowser.Navigate2(Location, Unassigned, Unassigned, Unassigned, Unassigned);
  finally
    VariantClear(Location);
  end;
  WebBrowser.Visible := True;
end;
{ translated from the link mentioned in this comment
  https://blogs.msdn.microsoft.com/oldnewthing/20040720-00/?p=38393 }
procedure BrowseInExplorer(const Folder: string);
var
  I: Integer;
  WndIface: IDispatch;
  ShellView: IShellView;
  FolderView: IFolderView;
  SrcFolderID: PItemIDList;
  CurFolderID: PItemIDList;
  ShellBrowser: IShellBrowser;
  ShellWindows: IShellWindows;
  WebBrowserApp: IWebBrowserApp;
  PersistFolder: IPersistFolder2;
  ServiceProvider: IServiceProvider;
begin
  SrcFolderID := GetFolderIDList(Folder);
  try
    OleCheck(CoCreateInstance(CLASS_ShellWindows, nil, CLSCTX_LOCAL_SERVER, IID_IShellWindows, ShellWindows));
    { iterate all Shell windows }
    for I := 0 to ShellWindows.Count - 1 do
    begin
      WndIface := ShellWindows.Item(VarAsType(I, VT_I4));
      { do not use OleCheck here; windows like Internet Explorer do not implement
        all the interfaces; it is the way to distinguish Windows Explorer windows
        actually; so let's get all the references and if we succeed, check if the
        obtained folder equals to the passed one; if so, bring that window to top
        and exit this procedure }
      if Assigned(WndIface) and
        Succeeded(WndIface.QueryInterface(IID_IWebBrowserApp, WebBrowserApp)) and
        Succeeded(WebBrowserApp.QueryInterface(IID_IServiceProvider, ServiceProvider)) and
        Succeeded(ServiceProvider.QueryService(SID_STopLevelBrowser, IID_IShellBrowser, ShellBrowser)) and
        Succeeded(ShellBrowser.QueryActiveShellView(ShellView)) and
        Succeeded(ShellView.QueryInterface(IID_IFolderView, FolderView)) and
        Succeeded(FolderView.GetFolder(IID_IPersistFolder2, PersistFolder)) and
        Succeeded(PersistFolder.GetCurFolder(CurFolderID)) and
        ILIsEqual(SrcFolderID, CurFolderID) then
      begin
        { restore the window if minimized, try to bring it to front and exit this
          procedure }
        if IsIconic(WebBrowserApp.HWnd) then
          Win32Check(ShowWindow(WebBrowserApp.HWnd, SW_RESTORE));
        {$IFNDEF IBelieveThatIWebBrowserAppVisiblePropertyBringsWindowToFront}
        Win32Check(SetForegroundWindow(WebBrowserApp.HWnd));
        {$ELSE}
        OleCheck(CoAllowSetForegroundWindow(WebBrowserApp, nil));
        WebBrowserApp.Visible := True;
        {$ENDIF}
        Exit;
      end;
    end;
    { the procedure was not exited, hence an existing window was not found, so go
      and open the new one }
    OpenNewExplorer(SrcFolderID);
  finally
    CoTaskMemFree(SrcFolderID);
  end;
end;
{$WARN SYMBOL_PLATFORM ON}
2025/10/01 11:23 2025/10/01 11:23
Article tag list Go to top
View Comment 0
Trackback URL :: 이 글에는 트랙백을 보낼 수 없습니다
 
 
 
 
: [1][2][3][4][5][6] ... [1335] :
«   2025/11   »
            1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30            
전체 (1335)
출판 준비 (0)
My-Pro... (41)
사는 ... (933)
블로그... (22)
My Lib... (32)
게임 ... (23)
개발관... (3)
Smart ... (1)
Delphi (93)
C Builder (0)
Object... (0)
VC, MF... (10)
Window... (1)
Open API (3)
Visual... (0)
Java, JSP (2)
ASP.NET (0)
PHP (6)
Database (12)
리눅스 (29)
Windows (30)
Device... (1)
Embedded (1)
게임 ... (0)
Web Se... (2)
Web, S... (21)
잡다한... (7)
프로젝트 (0)
Personal (0)
대통령... (13)
Link (2)