In my hello world console app, Process.GetCurrentProcess().Id
property returns a different value from the Id
for the Console
window created to display the app's stdout etc.
How do I get the process id for the console window specifically?
I cycle through the processes in Process.GetProcesses()
and check for the console window based on window title. When it finds it, I print it's process id out and it's different to what is returned from the GetCurrentProcess()
call. So I'm concluding the console app process and the console window are two different processes, maybe the console window is a child process of my console app, or maybe it's a peculiarity associated with running a console app from within 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!!!
}
}
}