-
Notifications
You must be signed in to change notification settings - Fork 1
/
Tools.cs
87 lines (75 loc) · 3.06 KB
/
Tools.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
using SHDocVw;
using Shell32;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace NewFileTool
{
public class Tools
{
/// <summary>
/// The main code for this method is from <see href="https://stackoverflow.com/questions/20960316/get-folder-path-from-explorer-window">StackOverflow</see>, i just made some modifications for better intellisense.
/// </summary>
/// <returns></returns>
public static string LocatePath(string WindowName)
{
if (string.IsNullOrWhiteSpace(WindowName))
return default;
string DirectoryPath = null;
IntPtr MyHwnd = NativeMethods.FindWindow(null, WindowName);
if (MyHwnd == null)
return default;
//To get the Shell type, the ShellWindows type and the InternetExplorer type reference the following COM libraries:
//1- Microsoft Shell Controls And Automation
//2- Microsoft Internet Controls
//Note: You don't have to reference them i only did it for intellisense, you can just leave them as dynamic and compile.
var t = Type.GetTypeFromProgID("Shell.Application");
Shell o = (Shell)Activator.CreateInstance(t);
try
{
var ws = (ShellWindows)o.Windows();
for (int i = 0; i < ws.Count; i++)
{
var ie = (InternetExplorer)ws.Item(i);
if (ie == null || ie.HWND != (long)MyHwnd) continue;
var path = System.IO.Path.GetFileName((string)ie.FullName);
if (path.ToLower() == "explorer.exe")
{
if (!string.IsNullOrWhiteSpace(ie.LocationURL))
{
DirectoryPath = new Uri(ie.LocationURL).LocalPath;
}
}
}
}
finally
{
Marshal.FinalReleaseComObject(o);
}
return DirectoryPath;
}
public static string GetActiveWindowTitle()
{
var Processes = Process.GetProcessesByName("explorer");
IntPtr ActiveWindowHandle = NativeMethods.GetForegroundWindow();
if (ActiveWindowHandle == null)
return default;
_ = NativeMethods.GetWindowThreadProcessId(new HandleRef(null, ActiveWindowHandle), out int processId);
foreach (var process in Processes)
{
if (process.Id == processId)
{
int length = NativeMethods.GetWindowTextLength(ActiveWindowHandle);
StringBuilder text = new StringBuilder(length + 1);
NativeMethods.GetWindowText(ActiveWindowHandle, text, text.Capacity);
return text.ToString();
}
}
return default;
}
}
}