Process started by Process.start() returns incorrect process ID?

An example of how I did it:

    bool started = false;
    var p = new Process();

    p.StartInfo.FileName = "notepad.exe";

    started = p.Start();

    try {
      var procId = p.Id;
      Console.WriteLine("ID: " + procId);
    }
    catch(InvalidOperationException)
    {
        started = false;
    }
    catch(Exception ex)
    {
        started = false;
    }

Otherwise, try using handles like this:
Using handlers
Getting handler

hWnd = (int) process.MainWindowHandle;
int processId;
GetWindowThreadProcessId(hWnd, out processId);

[DllImport("user32")]
static extern int GetWindowThreadProcessId(IntPtr hWnd, out int processId);

Side note:
What happens if you get the array of process and iterate over them and compare the PIDs?

Process[] p = Process.GetProcessesByName( "testprogram" );
foreach(var proc in p)
    Console.WriteLine("Found: "+proc.Id == myExpectedProcId);

This:

using (Process process = Process.Start("notepad.exe"))
{
    process.WaitForInputIdle();
    Console.WriteLine(process.Id);
}

Actually works for me:

http://pasteboard.s3.amazonaws.com/images/1350293463417532.png

Task Manager:

http://pasteboard.s3.amazonaws.com/images/1350293536498959.png

My thoughts:

Actually your process starts another process and you are trying to get ID of some kind of launcher. (It can start itself by the way).


Below also returns the PID of a process

Process[] p = Process.GetProcessesByName("YourProcessName");

Now you can get process Id by using p[i].Id;