2012-07-14 208 views
2

我想知道如何使用C#獲取當前活動窗口的路徑。使用窗口句柄獲取當前活動窗口的路徑

我得到currnet活動窗口

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

     handle = GetForegroundWindow(); 

的手柄現在我該怎樣得到這個窗口的路徑?

即: 「我的文檔」 窗口的路徑是

C:\Users\User\Documents 

- == - == - ==編輯 - == - == - = -
我想要監視程序來監視「Windows資源管理器」,並查看用戶去哪裏?
(即:用戶轉至c:\,然後轉到程序文件,然後轉到Internet Explorer和我想這個路徑:C:\ Program Files文件\ Internet Explorer中 enter image description here

+3

Windows沒有路徑。使用該窗口的進程具有當前路徑。你需要獲得這個過程。 – stark 2012-07-14 14:29:42

+0

可能是重複的http://stackoverflow.com/questions/2265647/how-can-i-get-the-exe-path-of-the-foreground-window – Ria 2012-07-14 14:36:05

+0

@Ria:這是不重複我想找到一個當前窗口的「Windows資源管理器」的路徑。你知道我嗎? – AminM 2012-07-14 17:14:42

回答

5

添加引用( COM)以 「Microsoft Internet控制」

var explorer = new SHDocVw.ShellWindowsClass().Cast<SHDocVw.InternetExplorer>().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例如與主窗口句柄的標題/路徑handle

+0

VS2010給我2錯誤:類型'SHDocVw.ShellWindowsClass'沒有定義的構造函數,Interop類型'SHDocVw.ShellWindowsClass'不能被嵌入。改爲使用適用的界面 – AminM 2012-07-14 18:24:33

+1

在引用的(shdocvw)屬性中禁用「嵌入互操作類型」。 (您將需要分發interop dll) – 2012-07-14 18:27:24

+1

我只需要更改爲SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindows(); (來自ShellWindowsClass())換句話說,使用接口而不是Class。 – blak3r 2013-01-08 05:50:02

-1

使用線程...

   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<SHDocVw.InternetExplorer>().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();