用于打开Windows资源管理器(或焦点,如果存在)并选择文件的代码

时间:2013-01-30 09:51:38

标签: c# .net directory explorer windows-explorer

我的目标是编写一个C#代码,打开一个Windows资源管理器窗口,并选择一个特定的文件。如果这样的窗户已经打开,我想把它带到前面。我尝试过两种选择。

首先,我首先明确调用explorer.exe

arg = "/select, " + pathToFile;
Process.Start("explorer.exe", arg);

这会打开并选择一个正常的窗口,但问题是它将始终打开一个新窗口,即使存在一个窗口。所以我尝试了这个:

Process.Start(pathToDir);

这会打开一个新窗口或聚焦一个旧窗口,但我没有选择文件的选项。

我该怎么办?我看了explorer's arguments,我看不到任何可以用的东西。我能想出的最后一个选择是获取已经打开的窗口列表并使用一些WINAPI级别的代码来处理它,但这看起来有点矫枉过正。

1 个答案:

答案 0 :(得分:12)

我不知道是否可以使用进程启动,但以下代码仅在需要时打开包含文件夹的Windows资源管理器(如果文件夹已打开,或在另一个文件中选中,则重复使用)并选择想要的文件。

它在SHOpenFolderAndSelectItems function上使用p / invoke互操作代码:

public static void OpenFolderAndSelectFile(string filePath)
{
    if (filePath == null)
        throw new ArgumentNullException("filePath");

    IntPtr pidl = ILCreateFromPathW(filePath);
    SHOpenFolderAndSelectItems(pidl, 0, IntPtr.Zero, 0);
    ILFree(pidl);
}

[DllImport("shell32.dll", CharSet = CharSet.Unicode)]
private static extern IntPtr ILCreateFromPathW(string pszPath);

[DllImport("shell32.dll")]
private static extern int SHOpenFolderAndSelectItems(IntPtr pidlFolder, int cild, IntPtr apidl, int dwFlags);

[DllImport("shell32.dll")]
private static extern void ILFree(IntPtr pidl);