我需要杀死特定文件上的所有Microsoft Word进程
我有一个隔夜工作,打开文件并编辑它们然后再次关闭它们。
private void killprocess(string p)
{
foreach (Process proc in Process.GetProcessesByName(p).OrderBy(x=>x.Id))
{
proc.Kill();
}
}
此方法会杀死具有特定名称的所有进程,在这种情况下p =“winword” 但是......我想杀死p =“winword”和FilePath =“C:\ Temp \ Test.docx”的所有进程。有什么想法吗?
答案 0 :(得分:1)
如果用户双击该文件并打开WinWord,那么它将作为命令行传递。
您可以尝试以下操作:
private static void Killprocess(string processName, string expectedCommandLine)
{
foreach (Process proc in Process.GetProcessesByName(processName).OrderBy(x => x.Id))
{
var commandLine = GetCommandLine(proc);
if (commandLine.Contains(expectedCommandLine))
{
proc.Kill();
}
}
}
private static string GetCommandLine(Process process)
{
string wmiQuery = string.Format("select CommandLine from Win32_Process where ProcessId={0}", process.Id);
ManagementObjectSearcher searcher = new ManagementObjectSearcher(wmiQuery);
ManagementObjectCollection result = searcher.Get();
return result.Cast<ManagementObject>()
.Select(x => x["CommandLine"].ToString())
.FirstOrDefault();
}
private static void Main()
{
Killprocess("winword", yourfullFilePath);
}
注意:如果用户通过菜单打开文件,则需要更多工作。 You need to find whether a process(Winword) has open file handle to the file你很关心。一旦你发现你可以杀死它。
答案 1 :(得分:0)
private void KillWordByDocumentName(string FullPath)
{
object document = null;
object word = null;
try
{
document = Microsoft.VisualBasic.Interaction.GetObject(FullPath, null);
word = document.GetType().InvokeMember("Parent", BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Public, null, document, null);
word.GetType().InvokeMember("Quit", BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public | BindingFlags.OptionalParamBinding, null, word, new object[] { true });
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
// No words are running
}
finally
{
if (document != null) System.Runtime.InteropServices.Marshal.FinalReleaseComObject(document);
if (word != null) System.Runtime.InteropServices.Marshal.FinalReleaseComObject(word);
}
}
如果Word拒绝杀死(例如从对象中获取进程ID并将其删除),则需要做更多工作
在这方面Excel比Word好得多,它直接暴露了hWnd
。