2012-07-14 206 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();