使用窗口句柄获取当前活动窗口的路径

我想知道如何使用C#获取当前活动窗口的路径。

我得到currnet活动窗口的句柄

const int nChars = 256; int handle = 0; StringBuilder Buff = new StringBuilder(nChars); handle = GetForegroundWindow(); 

现在我怎么得到这个窗口的路径?

ie:“我的文档”窗口的路径是

 C:\Users\User\Documents 

– == – == – ==编辑- == – == – = –
我想用程序监控“Windows资源管理器”并查看用户去哪里?
(即:用户转到c:\然后转到程序文件,然后转到Internet Explorer,我想获得此路径:C:\ Program Files \ Internet Explorer。 在此处输入图像描述

添加引用(COM)到“Microsoft Internet Controls”

 var explorer = new SHDocVw.ShellWindowsClass().Cast().Where(hwnd => hwnd.HWND == handle).FirstOrDefault(); if (explorer != null) { string path = new Uri(explorer.LocationURL).LocalPath; Console.WriteLine("name={0}, path={1}", explorer.LocationName, path); } 

使用句柄中的主窗口句柄打印explorer.exe实例的标题/路径。

用一个线程……

  Exception threadEccezione = null; System.Threading.Thread staThread = new System.Threading.Thread( delegate() { try { //SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindows(); var explorer = new SHDocVw.ShellWindowsClass().Cast().Where(hwnd => hwnd.HWND == handle).FirstOrDefault(); if (explorer != null) { string path = new Uri(explorer.LocationURL).LocalPath; MessageBox.Show(path); } } catch (Exception ex) { threadEccezione = ex; } } ); ; staThread.Start(); staThread.Join();