您好,我有一个应用程序,可以显示您在PC中已安装的所有应用程序,例如:
google chrome Mozilla Firefox 63.0.3(x64 en-GB) 等等...
我想按名称获取每个应用程序的进程。 (例如Mozilla Firefox 63.0.3(x64 en-GB).getProcess())
感谢您的帮助。
答案 0 :(得分:0)
您可以获得所有进程的数组:
using System.Diagnostics;
...
Process[] allProcesses = Process.GetProcesses();
,然后对于每个进程,您都可以找到有关ProccessModule
的信息(例如,文件名,模块名...),该信息用于通过Process.MainModule
属性启动进程。 / p>
答案 1 :(得分:0)
您可以首先使用WMI和FileVersionInfo构建过程字典。
private static IList<ProcessInfo> BuildProcessDictionary()
{
var wmiQueryString = "SELECT ProcessId, ExecutablePath FROM Win32_Process";
using (var searcher = new ManagementObjectSearcher(wmiQueryString))
using (var results = searcher.Get())
{
var processList = from p in Process.GetProcesses()
join mo in results.Cast<ManagementObject>()
on p.Id equals (int)(uint)mo["ProcessId"]
select new ProcessInfo
{
Process = p,
Path = (string)mo["ExecutablePath"],
DisplayName = (string)mo["ExecutablePath"]!=null?FileVersionInfo.GetVersionInfo((string)mo["ExecutablePath"]).FileDescription:string.Empty
};
return processList.ToList();
}
return default;
}
public class ProcessInfo
{
public string Path { get; set; }
public string DisplayName { get; set; }
public Process Process { get; set; }
}
然后您可以查询集合
var processDictionary = BuildProcessDictionary();
var found = processDictionary.Where(x => x.DisplayName!=null && x.DisplayName.Equals("Google Chrome"));
更新
var listOfPrograms = new[] { "Google Chrome", "Notepad" };
var processDictionary = BuildProcessDictionary();
foreach (var item in listOfPrograms)
{
try
{
var programInstances = processDictionary.Where(x => x.DisplayName != null && x.DisplayName.Equals(item));
foreach (var programInstance in programInstances)
{
programInstance.Process.Kill();
}
}
catch (Exception )
{
// Log items that wasn't found or coudn't be killed.
Console.WriteLine($"Could not find or kill process {item}");
}
}