如何在C#console app中获取Console的进程ID

时间:2015-06-21 20:47:01

标签: c# process console-application managed pid

在我的hello world console应用程序中,Process.GetCurrentProcess().Id属性为Id窗口返回一个不同的值,用于显示应用程序的标准输出等的Console窗口。

如何具体获取控制台窗口的进程ID?

我循环浏览Process.GetProcesses()中的进程,并根据窗口标题检查控制台窗口。当它找到它时,我打印出它的进程id,它与GetCurrentProcess()调用返回的内容不同。所以我总结了控制台应用程序进程和控制台窗口是两个不同的进程,也许控制台窗口是我的控制台应用程序的子进程,或者它可能是从Visual Studio中运行控制台应用程序相关的特性。

        Process[] processlist = Process.GetProcesses();
        int origProcessId = Process.GetCurrentProcess().Id;
        foreach ( Process p in processlist)
        {
            // get all window handles of title 'C:\Windows\system32\cmd.exe
            if (!String.IsNullOrEmpty(p.MainWindowTitle) && p.MainWindowTitle.IndexOf("C:\\Windows\\system32\\cmd.exe") == 0 )
            {
                    Console.WriteLine("Gets here ok, once & only once");
                    if(origProcessId == p.Id){
                                Console.WriteLine("Process: {0}", p.Id); // doesn't get here!!!
                    }
            }
        }

1 个答案:

答案 0 :(得分:2)

我认为了解为什么你需要进程ID对我们有用。问题在于,您可以通过多种方式启动应用程序,并且每个方法看起来都会有所不同:

在Visual Studio中,使用调试运行

这将使您的应用程序在单个进程中运行。 MainWindowTitle将类似于以下内容:

file://C:\...\ConsoleApplication.exe

在Visual Studio中,无需调试即可运行

这将启动cmd.exe并启动您的应用程序。因此,您的应用程序将是一个与cmd.exe不同的进程,并且没有MainWindowTitle(因为它没有窗口)。您可以在Process Explorer中看到该进程作为cmd.exe的子进程运行:

enter image description here

没有Visual Studio:

当双击应用程序的exe时,您将获得一个进程,其MainWindowTitle将成为您的exe的路径(因此与第一个案例相同但没有{{1 }})。如果取消选中"启用Visual Studio托管过程"当您使用VS进行调试时,也可以使它像这样运行。在项目的调试选项中。

不使用Visual Studio,使用命令行

这将给你完全相同的结果VS"运行没有调试"选项。

我认为这里的重要信息是:不要使用file://来查找您的申请。 MainWindowTitle将始终为您提供当前进程ID。

如果由于某种原因,您想要找到父进程,我建议您查看this question。我想你应该澄清:为什么你需要找到进程ID吗?你想用它做什么?