本文介绍了我可以得到其他进程的命令行参数的.NET / C#?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个项目,我有一个应用程序运行多个实例,每个启动时使用不同的命令行参数。我希望有一种方法来点击一个按钮,从这些实例,然后关闭所有的实例之一,具有相同的命令行参数再次开始他们回来。

I have a project where I have multiple instances of an app running, each of which was started with different command line arguments. I'd like to have a way to click a button from one of those instances which then shuts down all of the instances and starts them back up again with the same command line arguments.

我可以通过获取过程本身很轻松了Process.GetProcessesByName(),但每当我做了, StartInfo.Arguments 属性始终是一个空字符串。它看起来像,也许该属性是唯一有效的启动过程之前。

I can get the processes themselves easily enough through Process.GetProcessesByName(), but whenever I do, the StartInfo.Arguments property is always an empty string. It looks like maybe that property is only valid before starting a process.

<一个href="http://stackoverflow.com/questions/440932/reading-command-line-arguments-of-another-process-win32-c-$c$c">This问题有一些建议,但他们都在本土code,我想直接从.NET做到这一点。有什么建议?

This question had some suggestions, but they're all in native code, and I'd like to do this directly from .NET. Any suggestions?

推荐答案

这是使用所有管理对象,但它确实沾下来到WMI境界:

This is using all managed objects, but it does dip down into the WMI realm:

private static void Main()
{
    foreach (var process in Process.GetProcesses())
    {
        try
        {
            Console.WriteLine(process.GetCommandLine());
        }
        catch (Win32Exception ex)
        {
            if ((uint)ex.ErrorCode != 0x80004005)
            {
                throw;
            }
        }
    }
}

private static string GetCommandLine(this Process process)
{
    var commandLine = new StringBuilder(process.MainModule.FileName);

    commandLine.Append(" ");
    using (var searcher = new ManagementObjectSearcher("SELECT CommandLine FROM Win32_Process WHERE ProcessId = " + process.Id))
    {
        foreach (var @object in searcher.Get())
        {
            commandLine.Append(@object["CommandLine"]);
            commandLine.Append(" ");
        }
    }

    return commandLine.ToString();
}

这篇关于我可以得到其他进程的命令行参数的.NET / C#?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 16:18