通過 winapi 呼叫(CreateProcessAsUserW例如)啟動行程時,您將獲得一個行程和執行緒句柄。有了這個,您可以獲得行程的 PID,然后您可以進行Process.GetProcessById呼叫。但是,當行程同時終止時,此呼叫將失敗。
有沒有辦法Process通過句柄來獲取物件?我現在GetExitCodeProcess用來至少獲取一些資訊,但我寧愿回傳一個Process帶有相關屬性集的物件。
uj5u.com熱心網友回復:
我通過執行以下操作“解決”了這個問題:
// Construct Process object through private constructor, taking the PID. This also works when the process has already exited.
Process new_process = Activator.CreateInstance(typeof(Process), BindingFlags.Instance | BindingFlags.NonPublic, null, new object[] { ".", false, (int)pid, null }, null, null) as Process;
// Wrap the handle and give ownership to wrapper
SafeProcessHandle safe_handle = new SafeProcessHandle((IntPtr)process_handle, true);
// Set interal process handle for Process object through private method. This prevents the .ExitCode accessor to throw an exception.
typeof(Process).GetMethod("SetProcessHandle", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(new_process, new object[] { safe_handle });
這行得通,但不是很好。因為它通過反射訪問兩個私有函式。有關 Process 物件內部的更多資訊,請查看此處。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/448923.html
