我有一个项目,其中运行了一个应用程序的多个实例,每个实例都是使用不同的命令行参数启动的。我希望有一种方法可以从其中一个实例中单击一个按钮,然后关闭所有实例并使用相同的命令行参数重新启动它们。
我可以通过 Process.GetProcessesByName()
轻松获取进程本身,但无论何时我这样做,StartInfo.Arguments
属性始终是一个空字符串。看起来该属性可能仅在启动流程之前有效。
This question有一些建议,但它们都是 native 代码,我想直接从 .NET 执行此操作。有什么建议吗?
最佳答案
这使用了所有托管对象,但它确实深入到 WMI 领域:
private static void Main()
{
foreach (var process in Process.GetProcesses())
{
try
{
Console.WriteLine(process.GetCommandLine());
}
catch (Win32Exception ex) when ((uint)ex.ErrorCode == 0x80004005)
{
// Intentionally empty - no security access to the process.
}
catch (InvalidOperationException)
{
// Intentionally empty - the process exited before getting details.
}
}
}
private static string GetCommandLine(this Process process)
{
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT CommandLine FROM Win32_Process WHERE ProcessId = " + process.Id))
using (ManagementObjectCollection objects = searcher.Get())
{
return objects.Cast<ManagementBaseObject>().SingleOrDefault()?["CommandLine"]?.ToString();
}
}
关于c# - 我可以从 .NET/C# 获取其他进程的命令行参数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2633628/