如何获取文件资源管理器打开窗口的目录?

时间:2016-09-04 09:15:57

标签: c# .net winforms

例如在任务栏上我右键单击文件资源管理器>文件资源管理器>打开,现在例如我在C:\

现在我想以某种方式使用csharp代码来获取此文件资源管理器打开的窗口目录,在这种情况下C:\如果我将打开文件资源管理器的新窗口,将转到c:\ temp,我将运行该程序现在我将拥有两个路径的两个字符串的数组或列表:窗口1:C:\ Window 2:C:\ Temp

我到现在为止尝试了什么:

在form1的顶部:

[DllImport("user32.dll", SetLastError = true)]
 static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

然后在构造函数中调用GetDirs:

public Form1()
        {
            InitializeComponent();

            GetDirs();
        }

然后方法GetDirs:

private void GetDirs()
        {
            IntPtr MyHwnd = FindWindow(null, "Directory");
            var t = Type.GetTypeFromProgID("Shell.Application");
            dynamic o = Activator.CreateInstance(t);
            try
            {
                var ws = o.Windows();
                for (int i = 0; i < ws.Count; i++)
                {
                    var ie = ws.Item(i);
                    if (ie == null || ie.hwnd != (long)MyHwnd) continue;
                    var path = System.IO.Path.GetFileName((string)ie.FullName);
                    if (path.ToLower() == "explorer.exe")
                    {
                        var explorepath = ie.document.focuseditem.path;
                    }
                }
            }
            finally
            {
                Marshal.FinalReleaseComObject(o);
            } 
        }

但它永远不会出现在这条线上:

var explorepath = ie.document.focuseditem.path;

我不确定什么类型的var是explorepath。

2 个答案:

答案 0 :(得分:2)

要在所有打开的资源管理器窗口中获取焦点项目的目录名:

        var t = Type.GetTypeFromProgID("Shell.Application");
        dynamic o = Activator.CreateInstance(t);
        try
        {
            var ws = o.Windows();
            for (int i = 0; i < ws.Count; i++)
            {
                var ie = ws.Item(i);
                if (ie == null) continue;
                var path = System.IO.Path.GetFileName((string)ie.FullName);
                if (path.ToLower() == "explorer.exe")
                {
                    var explorepath = System.IO.Path.GetDirectoryName(ie.document.focuseditem.path);
                }
            }
        }
        finally
        {
            Marshal.FinalReleaseComObject(o);
        }

我不确定您要使用FindWindow尝试实现的目标,这基本上就是我删除的内容。

答案 1 :(得分:1)

你试过Microsoft Internet Controls SHDocVw了吗?例如,此代码清单可以显示当前打开的目录的路径。

SHDocVw.ShellWindows shellWindows = null;
try
{
    shellWindows = new SHDocVw.ShellWindows();
    foreach (Set_folder_view_2.WinAPI._IServiceProvider serviceProvider in shellWindows)
    {
        SHDocVw.InternetExplorer ie = (SHDocVw.InternetExplorer)serviceProvider;

        if (Path.GetFileNameWithoutExtension(ie.FullName).Equals("explorer", StringComparison.OrdinalIgnoreCase))
        {
            Console.WriteLine(ie.LocationURL);
        }
    }
}
catch (Exception ex)
{
    Console.WriteLine(ex);
}
finally
{
    if (shellWindows != null)
    {
        Marshal.ReleaseComObject(shellWindows);
    }
}