编写针对 Windows 11 的程序来获取文件资源管理器中当前活动选项卡的路径
以下是一个示例程序,它可以获取 Windows 11 文件资源管理器中当前活动选项卡的路径:
using System;
using System.Runtime.InteropServices;
using System.Text;
class Program
{
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
[DllImport("user32.dll")]
private static extern int GetWindowTextLength(IntPtr hWnd);
static void Main(string[] args)
{
IntPtr hWnd = GetForegroundWindow();
int length = GetWindowTextLength(hWnd);
StringBuilder sb = new StringBuilder(length + 1);
GetWindowText(hWnd, sb, sb.Capacity);
string windowTitle = sb.ToString();
if (windowTitle.EndsWith("File Explorer"))
{
IntPtr handle = FindWindowEx(hWnd, IntPtr.Zero, "WorkerW", null);
if (handle != IntPtr.Zero)
{
handle = FindWindowEx(handle, IntPtr.Zero, "ReBarWindow32", null);
if (handle != IntPtr.Zero)
{
handle = FindWindowEx(handle, IntPtr.Zero, "Address Band Root", null);
if (handle != IntPtr.Zero)
{
length = SendMessage(handle, WM_GETTEXTLENGTH, IntPtr.Zero, IntPtr.Zero).ToInt32();
sb = new StringBuilder(length + 1);
SendMessage(handle, WM_GETTEXT, sb.Capacity, sb);
string path = sb.ToString().Replace("Address: ", "");
Console.WriteLine(path);
}
}
}
}
}
private const int WM_GETTEXT = 0x000D;
private const int WM_GETTEXTLENGTH = 0x000E;
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr SendMessage(IntPtr hWnd, int Msg, int wParam, StringBuilder lParam);
}
这个程序使用了 Windows API 来获取当前活动窗口的标题,然后检查它是否是文件资源管理器。如果是,它会搜索窗口中的子控件,找到地址栏控件,然后获取地址栏中的文本,这就是当前活动选项卡的路径
原文地址: https://www.cveoy.top/t/topic/hlmn 著作权归作者所有。请勿转载和采集!