/// <summary> /// Retrieves the name of the specified parent process. /// </summary> /// <param name="parentProcessId">The system-unique identifier of the parent process resource.</param> /// <returns> Returns the name of the parent process that created the calling application.</returns> /// <remarks> /// Because a parent process may be in another session <see cref="OpenProcessHandle"/> will fail. This method safely retrieves process information albeit more slowly. /// </remarks> internal static string?GetParentProcessName(int parentProcessId) { var snapshotHandle = IntPtr.Zero; try { snapshotHandle = CreateToolhelp32Snapshot(SnapshotFlags.Process | SnapshotFlags.NoHeaps, (uint)parentProcessId); var processEntry = new ProcessEntry32W(); processEntry.Size = Marshal.SizeOf <ProcessEntry32W>(); if (Process32FirstW(snapshotHandle, ref processEntry)) { do { if (processEntry.ProcessID == parentProcessId) { return(string.IsNullOrWhiteSpace(processEntry.szExeFile) ? null : Path.GetFileNameWithoutExtension(processEntry.szExeFile)); } }while (Process32NextW(snapshotHandle, ref processEntry)); } } finally { CloseHandle(snapshotHandle); } return(null); }
public static extern bool Process32NextW(IntPtr snapshot, ref ProcessEntry32W entry);
private static extern bool Process32FirstW(IntPtr snapshot, ref ProcessEntry32W entry);