我正在寻找一种方法来关闭打开某个文件夹的Windows资源管理器窗口。说 c:\users\bob\folder。我可以使用下面的代码关闭所有资源管理器,但这显然不是我想要做的。这可能吗?
foreach (Process p in Process.GetProcessesByName("explorer"))
{
p.Kill();
}
谢谢
让我大部分时间都在那里:http://omegacoder.com/?p=63
我找到了一种使用名为"Microsoft Internet Controls"的 COM 库的方法,它看起来更适合 Internet Explorer,但我放弃了尝试使用进程 ID 和MainWindowTitle
的东西,因为资源管理器.exe只对所有打开的窗口使用一个进程,我无法确定如何从中获取窗口标题文本或文件系统位置。
因此,首先,从 COM 选项卡添加对Microsoft Internet 控件的引用,然后:
using SHDocVw;
这个小例程为我做了一个技巧:
ShellWindows _shellWindows = new SHDocVw.ShellWindows();
string processType;
foreach (InternetExplorer ie in _shellWindows)
{
//this parses the name of the process
processType = Path.GetFileNameWithoutExtension(ie.FullName).ToLower();
//this could also be used for IE windows with processType of "iexplore"
if (processType.Equals("explorer") && ie.LocationURL.Contains(@"C:/Users/Bob"))
{
ie.Quit();
}
}
一个警告,可能是由于这个库面向IE,你必须在文件夹路径中使用正斜杠...... 这是因为从ie
对象返回的真正LocationURL
的形式是file:///C:/Users/...
我会尝试导入user32.dll并调用FindWindow或FindWindowByCaption,然后调用DestroyWindow。
有关 FindWindow 的信息在这里:http://www.pinvoke.net/default.aspx/user32.findwindow
这行得通。 这是杰夫·罗伊(Jeff Roe)帖子的后续。
// Find window by Caption only. Note you must pass IntPtr.Zero as the first parameter.
[DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
public static extern IntPtr FindWindowByCaption(IntPtr ZeroOnly, string lpWindowName);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, StringBuilder lParam);
// caption is the window title.
public void CloseWindowsExplorer(string caption)
{
IntPtr i = User32.FindWindowByCaption(IntPtr.Zero, caption);
if (i.Equals(IntPtr.Zero) == false)
{
// WM_CLOSE is 0x0010
IntPtr result = User32.SendMessage(i, 0x0010, IntPtr.Zero, null);
}
}
foreach (Process p in Process.GetProcessesByName("explorer"))
{
if (p.MainWindowTitle.Contains("YourFolderName"))
{
p.Kill();
}
}