如何打开文件资源管理器的目录?

本文关键字:资源管理器 何打开 文件 | 更新日期: 2023-09-27 18:05:39

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

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

我一直在尝试:

[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是explorpath

如何打开文件资源管理器的目录?

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

        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实现什么,这基本上是我删除的。

你试过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);
    }
}
相关文章: