- Notifications
You must be signed in to change notification settings - Fork 364
/
Copy pathFileExplorerHelper.cs
96 lines (84 loc) · 3.21 KB
/
FileExplorerHelper.cs
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
usingSystem;
usingSystem.Collections.Generic;
usingSystem.IO;
usingSystem.Linq;
usingWindows.Win32;
namespaceFlow.Launcher.Infrastructure
{
publicstaticclassFileExplorerHelper
{
/// <summary>
/// Gets the path of the file explorer that is currently in the foreground
/// </summary>
publicstaticstringGetActiveExplorerPath()
{
varexplorerWindow=GetActiveExplorer();
stringlocationUrl=explorerWindow?.LocationURL;
return!string.IsNullOrEmpty(locationUrl)?GetDirectoryPath(newUri(locationUrl).LocalPath):null;
}
/// <summary>
/// Get directory path from a file path
/// </summary>
privatestaticstringGetDirectoryPath(stringpath)
{
if(!path.EndsWith("\\"))
{
returnpath+"\\";
}
returnpath;
}
/// <summary>
/// Gets the file explorer that is currently in the foreground
/// </summary>
privatestaticdynamicGetActiveExplorer()
{
Typetype=Type.GetTypeFromProgID("Shell.Application");
if(type==null)returnnull;
dynamicshell=Activator.CreateInstance(type);
if(shell==null)
{
returnnull;
}
varexplorerWindows=newList<dynamic>();
varopenWindows=shell.Windows();
for(inti=0;i<openWindows.Count;i++)
{
varwindow=openWindows.Item(i);
if(window==null)continue;
// find the desired window and make sure that it is indeed a file explorer
// we don't want the Internet Explorer or the classic control panel
// ToLower() is needed, because Windows can report the path as "C:\\Windows\\Explorer.EXE"
if(Path.GetFileName((string)window.FullName)?.ToLower()=="explorer.exe")
{
explorerWindows.Add(window);
}
}
if(explorerWindows.Count==0)returnnull;
varzOrders=GetZOrder(explorerWindows);
returnexplorerWindows.Zip(zOrders).MinBy(x =>x.Second).First;
}
/// <summary>
/// Gets the z-order for one or more windows atomically with respect to each other. In Windows, smaller z-order is higher. If the window is not top level, the z order is returned as -1.
/// </summary>
privatestaticIEnumerable<int>GetZOrder(List<dynamic>hWnds)
{
varz=newint[hWnds.Count];
for(vari=0;i<hWnds.Count;i++)z[i]=-1;
varindex=0;
varnumRemaining=hWnds.Count;
PInvoke.EnumWindows((wnd,_)=>
{
varsearchIndex=hWnds.FindIndex(x =>newIntPtr(x.HWND)==wnd);
if(searchIndex!=-1)
{
z[searchIndex]=index;
numRemaining--;
if(numRemaining==0)returnfalse;
}
index++;
returntrue;
},IntPtr.Zero);
returnz;
}
}
}