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

4

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

我获取当前活动窗口的句柄。

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

        handle = GetForegroundWindow(); 

现在我该如何获取此窗口的路径?

例如:"我的文档"窗口的路径是

C:\Users\User\Documents

我想编写一个程序来监控“Windows资源管理器”,并查看用户去了哪里?例如,用户进入C:\,然后进入Program Files,然后进入Internet Explorer,我想获取此路径:C:\Program Files\Internet Explorer。

3
Windows没有路径,使用该窗口的进程有当前路径。您需要获取该进程。 - stark
如何获取前台窗口的exe路径? - Ria
@Ria:这不是重复的问题,我想要找到“Windows资源管理器”当前窗口的路径。你明白我的意思吗? - AminM
1
可能是一个重复的问题:如何在Windows资源管理器中获取窗口的完整路径 - tenfour
2个回答

7

添加一个对“Microsoft Internet Controls” (COM) 的引用

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


VS2010 给了我两个错误:类型“SHDocVw.ShellWindowsClass”没有定义构造函数,且互操作类型“SHDocVw.ShellWindowsClass”无法被嵌入。请改用适当的接口。 - AminM
1
在引用(shdocvw)属性中禁用“嵌入互操作类型”(embed interop types)。(您需要分发interop dll) - Alex K.
1
我只需要将SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindows();更改为使用接口而不是类(即从ShellWindowsClass())。 - blak3r

-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();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接