I am starting an executable using this code:
Process proc = new Process();
proc.StartInfo.FileName = executablePath;
proc.Start();
proc.WaitForInputIdle();
<
I'm just trying to guess here, since it's difficult to understand what's really happening without seeing the real code. Anyway, you mentioned Trhreads in one of your comment. Is it possible that you have a single variable proc of type Process which is initialized in your main thread, and then the process is started in a different Thread?
If this is the case, maybe the process is started more than once, and you get the PID of just one of them. The only way I was able to reproduce your case is this one:
private Process proc;
private List<int> pids = new List<int>();
public void StartProc()
{
// this tries to simulate what you're doing. Starts the process, then
// wait to be sure that the second process starts, then kill proc
proc.Start();
pids.Add(proc.Id);
Thread.Sleep(300);
try
{
proc.Kill();
}
catch {}
}
// the method returns the PID of the process
public int Test()
{
proc = new Process();
proc.StartInfo.FileName = @"notepad.exe";
for (int i = 0; i < 2; i++)
{
Thread t = new Thread(StartProc);
t.Start();
Thread.Sleep(200);
}
Thread.Sleep(500);
return proc.Id;
}
When you executes Test, you should see a single active Notepad, and the PID returned by the method is different by the one showed by the Task Manager. But if you take a look at the pids List, you should see that the Task Manager PID is the first element in the list, and the one returned by the method is the second one.
Is it possible that you have done something similar?
Below also returns the PID of a process
Process[] p = Process.GetProcessesByName("YourProcessName");
Now you can get process Id by using p[i].Id;
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
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).
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);