[英]Is there a way to close a particular instance of explorer with C#?
我正在寻找一种方法来关闭对某个文件夹打开的 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
东西,因为 explorer.exe 只对所有打开的窗口使用一个进程,而我不能没有确定如何从中获取窗口标题文本或文件系统位置。
因此,首先,从 COM 选项卡添加对 Microsoft Internet Controls 的引用,然后:
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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.