public static Dictionary<UInt32, process> getProcessNameList() { int iCnt = 0; //List<processnames> name_list = new List<processnames>(); Dictionary<UInt32, process> _pList = new Dictionary<uint, process>(); uint procID = 0; IntPtr pHandle = CreateToolhelp32Snapshot(SnapshotFlags.Process | SnapshotFlags.NoHeaps, procID); if ((Int32)pHandle == INVALID_HANDLE_VALUE) throw new Exception("CreateToolhelp32Snapshot error: " + Marshal.GetLastWin32Error().ToString()); if ((int)pHandle != INVALID_HANDLE_VALUE) { PROCESSENTRY32 pEntry = new PROCESSENTRY32(); pEntry.dwSize = (uint)Marshal.SizeOf(pEntry); if (Process32First(pHandle, ref pEntry) == 1) { do { //name_list.Add(new processnames(pEntry.th32ProcessID, pEntry.szExeFile)); _pList[pEntry.th32ProcessID] = new process(pEntry.th32ProcessID, pEntry.szExeFile, new List<thread>()); iCnt++; } while (Process32Next(pHandle, ref pEntry) == 1); } else System.Diagnostics.Debug.WriteLine("Process32First error: " + Marshal.GetLastWin32Error().ToString()); CloseToolhelp32Snapshot(pHandle); } return _pList; }
static Dictionary<int,List<int>> GetProcRelations () { Dictionary<int,List<int>> procRelations = new Dictionary<int, List<int>> (); IntPtr oHnd = CreateToolhelp32Snapshot (TH32CS_SNAPPROCESS, 0); if (oHnd == IntPtr.Zero) return procRelations; PROCESSENTRY32 oProcInfo = new PROCESSENTRY32 (); oProcInfo.dwSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf (typeof(PROCESSENTRY32)); if (Process32First (oHnd, ref oProcInfo) == false) return procRelations; do { List<int> children; if (!procRelations.TryGetValue ((int)oProcInfo.th32ParentProcessID, out children)) { children = new List<int> (); procRelations [(int)oProcInfo.th32ParentProcessID] = children; } children.Add ((int)oProcInfo.th32ProcessID); } while (Process32Next (oHnd, ref oProcInfo)); return procRelations; }
//Fonction qui affiche les processus dans la listview et qui les met dans la liste public static void GetProcessList(ref ListView ProcessListView) { //on va dresser une liste de tout les processus ouverts IntPtr hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); //structure qui va contenir le nom, pid etc... de chaque processus PROCESSENTRY32 Pe = new PROCESSENTRY32(); Pe.dwSize = Marshal.SizeOf(Pe); //on commence par le premier processus bool ret = Process32First(hSnapshot, ref Pe); //on va boucler tout les processus while (ret) { //on ajoute le processus dans notre liste de processus ProcessList.Add(Pe); //on ajoute le processus dans notre listview ListViewItem Item = new ListViewItem(Pe.szExeFile); //son nom ProcessListView.Items.Add(Item); //ajout //prochain processus ret = Process32Next(hSnapshot, ref Pe); } //on ferme l'handle snapshot CloseHandle(hSnapshot); }
private static Process ParentProcess(this Process process) { #if __MonoCS__ // TODO: find a way to implement this in mono on a mac/linux machine return null; #else var parentPid = 0; var processPid = process.Id; const uint TH32_CS_SNAPPROCESS = 2; // Take snapshot of processes var hSnapshot = CreateToolhelp32Snapshot(TH32_CS_SNAPPROCESS, 0); if (hSnapshot == IntPtr.Zero) { return null; } var procInfo = new PROCESSENTRY32 { dwSize = (uint)Marshal.SizeOf(typeof(PROCESSENTRY32)) }; // Read first if (Process32First(hSnapshot, ref procInfo) == false) { return null; } // Loop through the snapshot do { // If it's me, then ask for my parent. if (processPid == procInfo.th32ProcessID) { parentPid = (int)procInfo.th32ParentProcessID; } } while (parentPid == 0 && Process32Next(hSnapshot, ref procInfo)); // Read next if (parentPid <= 0) { return null; } try { return Process.GetProcessById(parentPid); } catch (ArgumentException) { //Process with an Id of X is not running return null; } #endif }
/// <summary> /// Create a new process tree. This process tree stores all parent/child /// process relationships of the time when this process tree was created. /// </summary> public ProcessTree() { PROCESSENTRY32 procEntry = new PROCESSENTRY32(); procEntry.dwSize = (UInt32)Marshal.SizeOf(typeof(PROCESSENTRY32)); IntPtr handleToSnapshot = CreateToolhelp32Snapshot((uint)SnapshotFlags.Process, 0); if (!Process32First(handleToSnapshot, ref procEntry)) throw new Win32Exception(); do { parents.Add(procEntry.th32ProcessID, procEntry.th32ParentProcessID); } while (Process32Next(handleToSnapshot, ref procEntry)); CloseHandle(handleToSnapshot); }
/// <summary>Retrieves information about the next process encountered in a system snapshot.</summary> /// <param name="hSnapshot"> /// A handle to the snapshot returned from a previous call to the /// <see cref="CreateToolhelp32Snapshot" /> function. /// </param> /// <returns> /// The next <see cref="PROCESSENTRY32" /> if there was any or <see langword="null" /> otherwise (No more values /// in the snapshot). /// </returns> /// <exception cref="Win32Exception">Thrown if any error occurs.</exception> /// <exception cref="ArgumentNullException">If <paramref name="hSnapshot" /> is <see langword="null" />.</exception> public static PROCESSENTRY32 Process32Next(SafeObjectHandle hSnapshot) { if (hSnapshot == null) { throw new ArgumentNullException(nameof(hSnapshot)); } var entry = new PROCESSENTRY32(); if (Process32Next(hSnapshot, entry)) { return entry; } var lastError = GetLastError(); if (lastError != Win32ErrorCode.ERROR_NO_MORE_FILES) { throw new Win32Exception(lastError); } return null; }
public static List<Process> GetChildsOfProcess(Process parent) { var childs = new List<Process>(); var procEntry = new PROCESSENTRY32(); procEntry.dwSize = (UInt32)Marshal.SizeOf(typeof(PROCESSENTRY32)); var handleToSnapshot = CreateToolhelp32Snapshot(SnapshotFlags.Process, 0); if (!Process32First(handleToSnapshot, ref procEntry)) { throw new Win32Exception(); } do { if (procEntry.th32ParentProcessID == parent.Id) { childs.Add(Process.GetProcessById((int)procEntry.th32ProcessID)); } } while (Process32Next(handleToSnapshot, ref procEntry)); return childs; }
protected static extern int Process32Next(ToolHelpHandle hSnapshot, ref PROCESSENTRY32 lppe);
private static extern bool Process32Next(IntPtr Handle, ref PROCESSENTRY32 lppe);
public static extern bool Process32Next([System.Runtime.InteropServices.InAttribute()] System.IntPtr hSnapshot, ref PROCESSENTRY32 lppe);
public static extern Boolean Process32First( [In] IntPtr hSnapshot, ref PROCESSENTRY32 lppe );
/// <summary> /// Get the Process ID of the parent process of this one (which should be the console window) /// </summary> /// <returns></returns> static int GetParentProcId() { // First we need the current process id. int pid = System.Diagnostics.Process.GetCurrentProcess().Id; // Now get a snapshot of the currently-running processes PROCESSENTRY32 procEntry = new PROCESSENTRY32(); procEntry.dwSize = (UInt32)Marshal.SizeOf(typeof(PROCESSENTRY32)); IntPtr snap = CreateToolhelp32Snapshot(SnapshotFlags.Process, 0); // Loop through each process (if the initial call succeeds) if(Process32First(snap, ref procEntry)) { do { // Search for our specific process if(pid == procEntry.th32ProcessID) { // If we find it, return our parent process id return (int)procEntry.th32ParentProcessID; } } while(Process32Next(snap, ref procEntry)); } throw new ApplicationException("Can't get parent process id."); }
public static List <RunningProcess> StartAudit() { IntPtr handleToSnapshot = IntPtr.Zero; List <RunningProcess> prelem = new List <RunningProcess>(); Dictionary <string, Forensics.CryptInfo> lstCertInfo = new Dictionary <string, Forensics.CryptInfo>(); try { PROCESSENTRY32 procEntry = new PROCESSENTRY32(); procEntry.dwSize = (UInt32)Marshal.SizeOf(typeof(PROCESSENTRY32)); handleToSnapshot = CreateToolhelp32Snapshot((uint)SnapshotFlags.Process, 0); if (Process32First(handleToSnapshot, ref procEntry)) { do { RunningProcess pre = new RunningProcess(); pre.ListProcessModule = new List <LoadedModule>(); pre.PID = procEntry.th32ProcessID; pre.ProcessName = procEntry.szExeFile; pre.PPID = procEntry.th32ParentProcessID; pre.ParentName = GetMainModuleFilepath((int)pre.PPID); string s1 = winaudits.ProcessList.GetProcessParametersString((int)procEntry.th32ProcessID, PEB_OFFSET.CommandLine, pre); if (!string.IsNullOrEmpty(pre.Path)) { Forensics.CryptInfo ci; if (lstCertInfo.ContainsKey(pre.Path)) { ci = lstCertInfo[pre.Path]; } else { ci = Forensics.SigVerify.CheckSignatureForFile(pre.Path); ci.MD5 = Forensics.ProxyMD5.ComputeFileMD5(pre.Path); lstCertInfo.Add(pre.Path, ci); } pre.MD5 = ci.MD5; pre.IsSigned = ci.IsSigned; pre.IsVerified = ci.IsVerified; pre.CertSubject = ci.Subject; pre.CA = ci.CA; pre.SignatureString = ci.Signature; } foreach (var modu in pre.ListProcessModule) { modu.ProcessId = (int)pre.PID; if (!string.IsNullOrEmpty(modu.ModulePath)) { modu.ModuleName = Path.GetFileName(modu.ModulePath); } Forensics.CryptInfo ci; if (lstCertInfo.ContainsKey(modu.ModulePath)) { ci = lstCertInfo[modu.ModulePath]; } else { ci = Forensics.SigVerify.CheckSignatureForFile(modu.ModulePath); ci.MD5 = Forensics.ProxyMD5.ComputeFileMD5(modu.ModulePath); lstCertInfo.Add(modu.ModulePath, ci); } modu.MD5 = ci.MD5; modu.IsSigned = ci.IsSigned; modu.IsVerified = ci.IsVerified; modu.CertSubject = ci.Subject; modu.CA = ci.CA; modu.SignatureString = ci.Signature; } prelem.Add(pre); } while (Process32Next(handleToSnapshot, ref procEntry)); } } catch (Exception) { return(prelem); } finally { // Must clean up the snapshot object! CloseHandle(handleToSnapshot); } return(prelem); }
public static extern bool Process32Next(HSNAPSHOT hSnapshot, ref PROCESSENTRY32 lppe);
private static Process ParentProcess(Process process) { var parentPid = 0; var processPid = process.Id; const uint TH32_CS_SNAPPROCESS = 2; // Take snapshot of processes var hSnapshot = CreateToolhelp32Snapshot(TH32_CS_SNAPPROCESS, 0); if (hSnapshot == IntPtr.Zero) { return(null); } var procInfo = new PROCESSENTRY32 { dwSize = (uint)Marshal.SizeOf(typeof(PROCESSENTRY32)) }; // Read first if (Process32First(hSnapshot, ref procInfo) == false) { return(null); } // Loop through the snapshot do { // If it's me, then ask for my parent. if (processPid == procInfo.th32ProcessID) { parentPid = (int)procInfo.th32ParentProcessID; } } while (parentPid == 0 && Process32Next(hSnapshot, ref procInfo)); // Read next if (parentPid <= 0) { return(null); } try { return(Process.GetProcessById(parentPid)); } catch (ArgumentException) { //Process with an Id of X is not running return(null); } }
static extern int Process32Next([In] IntPtr hSnapshot, ref PROCESSENTRY32 lppe);
private static extern int ProcessFirst(int hSnapShot, ref PROCESSENTRY32 uProcess);
static public extern bool Process32Next(ToolHelpHandle hSnapshot, ref PROCESSENTRY32 lppe);
private static extern int Process32First(IntPtr hSnapshot, ref PROCESSENTRY32 lppe);
internal static extern bool Process32Next(IntPtr hSnapshot, ref PROCESSENTRY32 lppe);
public static extern int Process32Next(uint hSnapshot, ref PROCESSENTRY32 lppe);
static public extern bool Process32Next(int hSnapshot, ref PROCESSENTRY32 lppe);
private static extern bool Process32First([In] IntPtr hSnapshot, ref PROCESSENTRY32 lppe);
public static extern Boolean Process32Next( IntPtr hSnapshot, ref PROCESSENTRY32 lppe );
/* * ********************************************************************** * ********************************************************************** */ /// <summary> Enumerate all or find a processe(s) in the system. /// enumCallBack is called every time process is found </summary> /// <param name="enumCallBack">Delegate to callback method called each time a process is found</param> /// <param name="mode">Working switch:: Find_ALL=Gets all process, FindByPid, FindByName</param> /// <param name="procPID">PID of process in FIND_BY_PID; 0 if in FIND_ALL mode</param> /// <param name="procName">Name of process in FIND_BY_NAME; empty string if in FIND_ALL mode</param> /// <returns></returns> private static bool EnumerateProcess(EnumProcess_Callback enumCallBack, UInt32 procPID = 0, string procName = "", ENUMERATION_MODE mode = ENUMERATION_MODE.FIND_ALL) { Contract.Requires(enumCallBack != null); bool findMode = (mode != ENUMERATION_MODE.FIND_ALL) ? true : false; bool findByName = (mode == ENUMERATION_MODE.FIND_BY_NAME) ? true : false; bool status = false; if (findMode || findByName) { procPID = 0; } IntPtr hSnap = CreateToolhelp32Snapshot(SNAPSHOT_TYPE.TH32CS_SNAPPROCESS, (int)procPID); // Take Process Snapshot if (hSnap != IntPtr.Zero) // Validate handle to snapshot { PROCESSENTRY32 entry = new PROCESSENTRY32 { }; entry.dwSize = (uint)Marshal.SizeOf(typeof(PROCESSENTRY32)); ProcessInfo processInfo = new ProcessInfo(); bool validEntry = Process32First(hSnap, ref entry); // Get first entry in the snapshot if (!findMode && validEntry) { status = true; // Atleast 1 entry found in Find_All mode } while (validEntry) { string pName = Encoding.ASCII.GetString(entry.szExeFile).TrimStart('\0'); // Get Name of current snapshot entry pName = pName.Substring(0, pName.IndexOf('\0')); if (findMode) // Search Mode { if (findByName) { if (pName.ToLower().Contains(procName.ToLower())) // search by name { validEntry = Process32Next(hSnap, ref entry); status = true; continue; } } else { if (entry.th32ProcessID != procPID) // Search by PID { validEntry = Process32Next(hSnap, ref entry); status = true; continue; } } } processInfo.updateInfo(entry.th32ProcessID, pName); enumCallBack(processInfo); // Call the callback validEntry = Process32Next(hSnap, ref entry); // Get next entry in the snapshot } } CloseHandle(hSnap); return(status); }
public static bool CreateProcessInConsoleSession(String CommandLine, bool bElevate) { PROCESS_INFORMATION pi; bool bResult = false; uint dwSessionId, winlogonPid = 0; IntPtr hUserToken = IntPtr.Zero, hUserTokenDup = IntPtr.Zero, hPToken = IntPtr.Zero, hProcess = IntPtr.Zero; Debug.Print("CreateProcessInConsoleSession"); // Log the client on to the local computer. dwSessionId = WTSGetActiveConsoleSessionId(); // Find the winlogon process var procEntry = new PROCESSENTRY32(); uint hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (hSnap == INVALID_HANDLE_VALUE) { return(false); } procEntry.dwSize = (uint)Marshal.SizeOf(procEntry); //sizeof(PROCESSENTRY32); if (Process32First(hSnap, ref procEntry) == 0) { return(false); } String strCmp = "explorer.exe"; do { if (strCmp.IndexOf(procEntry.szExeFile) == 0) { // We found a winlogon process...make sure it's running in the console session uint winlogonSessId = 0; if (ProcessIdToSessionId(procEntry.th32ProcessID, ref winlogonSessId) && winlogonSessId == dwSessionId) { winlogonPid = procEntry.th32ProcessID; break; } } }while (Process32Next(hSnap, ref procEntry) != 0); //Get the user token used by DuplicateTokenEx WTSQueryUserToken(dwSessionId, ref hUserToken); var si = new STARTUPINFO(); si.cb = Marshal.SizeOf(si); si.lpDesktop = "winsta0\\default"; var tp = new TOKEN_PRIVILEGES(); var luid = new LUID(); hProcess = OpenProcess(MAXIMUM_ALLOWED, false, winlogonPid); if ( !OpenProcessToken(hProcess, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY | TOKEN_DUPLICATE | TOKEN_ASSIGN_PRIMARY | TOKEN_ADJUST_SESSIONID | TOKEN_READ | TOKEN_WRITE, ref hPToken)) { Debug.Print(String.Format("CreateProcessInConsoleSession OpenProcessToken error: {0}", Marshal.GetLastWin32Error())); } if (!LookupPrivilegeValue(IntPtr.Zero, SE_DEBUG_NAME, ref luid)) { Debug.Print(String.Format("CreateProcessInConsoleSession LookupPrivilegeValue error: {0}", Marshal.GetLastWin32Error())); } var sa = new SECURITY_ATTRIBUTES(); sa.Length = Marshal.SizeOf(sa); if (!DuplicateTokenEx(hPToken, MAXIMUM_ALLOWED, ref sa, (int)SECURITY_IMPERSONATION_LEVEL.SecurityIdentification, (int)TOKEN_TYPE.TokenPrimary, ref hUserTokenDup)) { Debug.Print( String.Format( "CreateProcessInConsoleSession DuplicateTokenEx error: {0} Token does not have the privilege.", Marshal.GetLastWin32Error())); CloseHandle(hProcess); CloseHandle(hUserToken); CloseHandle(hPToken); return(false); } if (bElevate) { //tp.Privileges[0].Luid = luid; //tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; tp.PrivilegeCount = 1; tp.Privileges = new int[3]; tp.Privileges[2] = SE_PRIVILEGE_ENABLED; tp.Privileges[1] = luid.HighPart; tp.Privileges[0] = luid.LowPart; //Adjust Token privilege if ( !SetTokenInformation(hUserTokenDup, TOKEN_INFORMATION_CLASS.TokenSessionId, ref dwSessionId, (uint)IntPtr.Size)) { Debug.Print( String.Format( "CreateProcessInConsoleSession SetTokenInformation error: {0} Token does not have the privilege.", Marshal.GetLastWin32Error())); //CloseHandle(hProcess); //CloseHandle(hUserToken); //CloseHandle(hPToken); //CloseHandle(hUserTokenDup); //return false; } if ( !AdjustTokenPrivileges(hUserTokenDup, false, ref tp, Marshal.SizeOf(tp), /*(PTOKEN_PRIVILEGES)*/ IntPtr.Zero, IntPtr.Zero)) { int nErr = Marshal.GetLastWin32Error(); if (nErr == ERROR_NOT_ALL_ASSIGNED) { Debug.Print( String.Format( "CreateProcessInConsoleSession AdjustTokenPrivileges error: {0} Token does not have the privilege.", nErr)); } else { Debug.Print(String.Format("CreateProcessInConsoleSession AdjustTokenPrivileges error: {0}", nErr)); } } } uint dwCreationFlags = NORMAL_PRIORITY_CLASS | CREATE_NEW_CONSOLE; IntPtr pEnv = IntPtr.Zero; if (CreateEnvironmentBlock(ref pEnv, hUserTokenDup, true)) { dwCreationFlags |= CREATE_UNICODE_ENVIRONMENT; } else { pEnv = IntPtr.Zero; } // Launch the process in the client's logon session. bResult = CreateProcessAsUser(hUserTokenDup, // client's access token null, // file to execute CommandLine, // command line ref sa, // pointer to process SECURITY_ATTRIBUTES ref sa, // pointer to thread SECURITY_ATTRIBUTES false, // handles are not inheritable (int)dwCreationFlags, // creation flags pEnv, // pointer to new environment block null, // name of current directory ref si, // pointer to STARTUPINFO structure out pi // receives information about new process ); // End impersonation of client. //GetLastError should be 0 int iResultOfCreateProcessAsUser = Marshal.GetLastWin32Error(); //Close handles task CloseHandle(hProcess); CloseHandle(hUserToken); CloseHandle(hUserTokenDup); CloseHandle(hPToken); return((iResultOfCreateProcessAsUser == 0) ? true : false); }
public static bool IsProcessRunning(string applicationName) { IntPtr handle = IntPtr.Zero; try { // Create snapshot of the processes handle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); PROCESSENTRY32 info = new PROCESSENTRY32(); info.dwSize = (uint)System.Runtime.InteropServices. Marshal.SizeOf(typeof(PROCESSENTRY32)); // Get the first process int first = Process32First(handle, ref info); // While there's another process, retrieve it do { if (string.Compare(info.szExeFile, applicationName, true) == 0) { return true; } } while (Process32Next(handle, ref info) != 0); } catch { throw; } finally { // Release handle of the snapshot CloseHandle(handle); handle = IntPtr.Zero; } return false; }
/// <summary> /// 获取模块地址 /// </summary> /// <param name="PID">目标进程PID</param> /// <param name="ModuleName">需获取到的模块名</param> /// <returns>返回个int类型的吧.想怎么转换看你们自己了.</returns> private int GetModelAddress(IntPtr PID, string ModuleName) { PROCESSENTRY32 pr = new PROCESSENTRY32(); MODULEENTRY32 mo = new MODULEENTRY32(); IntPtr LM; if (ModuleName == "") { //如果模块空,直接88 返回-2 因为2.. return -2; } pr.dwSize = (uint)Marshal.SizeOf(typeof(PROCESSENTRY32)); LM = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, PID); if (LM.ToInt32() > 0) { mo.dwSize = (uint)Marshal.SizeOf(typeof(MODULEENTRY32)); if (Module32First(LM, ref mo)) { do { if (mo.szModule == ModuleName) { CloseHandle(LM); return mo.modBaseAddr.ToInt32(); } } while (Module32Next(LM, ref mo)); } CloseHandle(LM); } //获取不到.或者遍历不到.都返回-1 return -1; }
/// <summary> /// Gets a list of processes by executable name /// </summary> /// <param name="ExeName">ExeName</param> /// <returns>List of processes</returns> public Process[] GetProcessesByExe(string ExeName) { ArrayList procs = new ArrayList(); IntPtr hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (hSnapshot == IntPtr.Zero) return null; PROCESSENTRY32 pe = new PROCESSENTRY32(); pe.dwSize = 296;// sizeof( pe); // Clear the parent id's _parentids.Clear(); int retval = Process32First(hSnapshot, ref pe); while (retval != 0) { if (pe.szExeFile.ToLower() == ExeName.ToLower()) { try { Process proc = Process.GetProcessById((int)pe.th32ProcessID); procs.Add(proc); } catch { } } _parentids.Add(pe.th32ProcessID, pe.th32ParentProcessID); retval = Process32Next(hSnapshot, ref pe); } CloseHandle(hSnapshot); return (Process[])procs.ToArray(typeof(Process)); }
private static Process GetParentProcess() { int iParentPid = 0; int iCurrentPid = Process.GetCurrentProcess().Id; IntPtr oHnd = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (oHnd == IntPtr.Zero) return null; PROCESSENTRY32 oProcInfo = new PROCESSENTRY32(); oProcInfo.dwSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(PROCESSENTRY32)); if (Process32First(oHnd, ref oProcInfo) == false) return null; do { if (iCurrentPid == oProcInfo.th32ProcessID) iParentPid = (int)oProcInfo.th32ParentProcessID; } while (iParentPid == 0 && Process32Next(oHnd, ref oProcInfo)); if (iParentPid > 0) return Process.GetProcessById(iParentPid); else return null; }
static void Main(string[] args) { Console.Write("Desktop handle (" + GetThreadDesktop(GetCurrentThreadId()) + "): "); IntPtr Desktop = (IntPtr)uint.Parse(Console.ReadLine()); IntPtr snapshot = IntPtr.Zero; snapshot = CreateToolhelp32Snapshot((uint)SnapshotFlags.Process | (uint)SnapshotFlags.Thread, 0); List<uint> Procs = new List<uint>(); THREADENTRY32 proct = new THREADENTRY32(); proct.dwSize = (UInt32)Marshal.SizeOf(typeof(THREADENTRY32)); if (Thread32First(snapshot, ref proct)) { do { if (GetThreadDesktop(proct.th32ThreadID) == Desktop) { bool flag = true; foreach (uint i in Procs) if (i == proct.th32OwnerProcessID) { flag = false; break; } if (flag) Procs.Add(proct.th32OwnerProcessID); } } while (Thread32Next(snapshot, ref proct)); } //foreach (uint i in Procs) MessageBox.Show(i.ToString()); PROCESSENTRY32 proc = new PROCESSENTRY32(); proc.dwSize = (UInt32)Marshal.SizeOf(typeof(PROCESSENTRY32)); if (Process32First(snapshot, ref proc)) { do { bool flag = false; foreach (uint i in Procs) if (i == proc.th32ProcessID) { flag = true; break; } if (flag) Console.WriteLine("Proc id: " + proc.th32ProcessID + "\nProc name: " + proc.szExeFile); } while (Process32Next(snapshot, ref proc)); } else { throw new ApplicationException(string.Format("Failed with win32 error code {0}", Marshal.GetLastWin32Error())); } CloseHandle(snapshot); Console.ReadKey(); }
/// <summary> /// �q�v���Z�X(����)��擾���� /// </summary> /// <param name="i_Process"></param> /// <returns>Process[] �q�v���Z�X�I�u�W�F�N�g�z��</returns> public static System.Diagnostics.Process[] GetChileProcess( System.Diagnostics.Process i_Process ) { System.IntPtr a_hSnapShot = System.IntPtr.Zero; PROCESSENTRY32 a_Entry; System.Collections.ArrayList a_ProcessArray = null; try { a_hSnapShot = CreateToolhelp32Snapshot( SnapshotFlags.Process, 0 ); a_Entry = new PROCESSENTRY32(); a_Entry.dwSize = (uint)Memory.SizeOf( a_Entry ); a_ProcessArray = new System.Collections.ArrayList( 0 ); if ( Process32First( a_hSnapShot, ref a_Entry ) ) { /* ////////////////////////////////////////////////////// */ // �e�v���Z�XID���w�肵���v���Z�XID�ƈ�v����v���Z�X��z��֒lj����� do { if ( i_Process.Id == a_Entry.th32ParentProcessID ) { try { a_ProcessArray.Add( System.Diagnostics.Process.GetProcessById( (int)a_Entry.th32ProcessID ) ); } catch ( System.Exception ex ) { // ��O�������̓v���Z�X�z���N���A���ĊO�֗�O�𓊂��� a_ProcessArray.Clear(); throw ex; } finally { } } } while( Process32Next( a_hSnapShot, ref a_Entry ) ); /* ////////////////////////////////////////////////////// */ } } catch ( System.Exception ex ) { // ��O�������͔z���J�����ĊO�֗�O�𓊂��� a_ProcessArray = null; throw ex; } finally { CloseHandle( a_hSnapShot ); a_hSnapShot = System.IntPtr.Zero; } return (System.Diagnostics.Process[])a_ProcessArray.ToArray( typeof( System.Diagnostics.Process ) ); }
private static extern bool Process32Next(SafeKernelObjectHandle snapshot, ref PROCESSENTRY32 entry);
internal extern static bool Process32First(IntPtr hSnapshot, ref PROCESSENTRY32 lppe);
static extern int Process32First([In]IntPtr hSnapshot, ref PROCESSENTRY32 lppe);
public static extern bool Process32First( IntPtr hSnapshot, // HANDLE ref PROCESSENTRY32 lppe);
private static extern Int32 Process32Next(IntPtr hSnapshot, ref PROCESSENTRY32 lppe);
public static extern bool Process32Next( IntPtr hSnapshot, // HANDLE ref PROCESSENTRY32 lpProcessEntry32);
/* ////////////////////////////////////////////////////// */ /// <summary> /// �e�v���Z�X��擾���� /// </summary> /// <param name="i_Process">�q�v���Z�X�I�u�W�F�N�g</param> /// <returns>Process �e�v���Z�X�I�u�W�F�N�g ������Ȃ������ꍇ��null</returns> public static System.Diagnostics.Process GetParentProcess( System.Diagnostics.Process i_Process ) { System.Diagnostics.Process a_ResultProcess = null; // �ŏ�ʃv���Z�X���w�肳�ꂽ�ꍇ��null��Ԃ� if ( i_Process.Id == 0 ) { return a_ResultProcess; } // ���s���_�̃v���Z�X�X�i�b�v�V���b�g��쐬 System.IntPtr a_hSnapShot = System.IntPtr.Zero; PROCESSENTRY32 a_Entry; try { a_hSnapShot = CreateToolhelp32Snapshot( SnapshotFlags.Process, 0 ); a_Entry = new PROCESSENTRY32(); a_Entry.dwSize = (uint)Memory.SizeOf( a_Entry ); if ( Process32First( a_hSnapShot, ref a_Entry ) ) { /* ////////////////////////////////////////////////////// */ // �v���Z�XID����v�����ꍇ�A���̐e�v���Z�X��Ԃ����[�v�I�� do { if ( i_Process.Id == a_Entry.th32ProcessID ) { try { a_ResultProcess = System.Diagnostics.Process.GetProcessById( (int)a_Entry.th32ParentProcessID ); } catch( System.Exception ) { // �v���Z�XID����v���Z�X�I�u�W�F�N�g�̐����Ɏ��s������null��Ԃ� a_ResultProcess = null; } finally { } // �q�b�g����v���Z�X��1�����Ȃ̂ŁA�q�b�g�������_�Ń��[�v�I�� break; } } while ( Process32Next( a_hSnapShot, ref a_Entry ) ); /* ////////////////////////////////////////////////////// */ } } catch ( System.Exception ) { } finally { CloseHandle( a_hSnapShot ); a_hSnapShot = System.IntPtr.Zero; } // ��1��q�b�g���Ȃ������ꍇ��null��Ԃ� return a_ResultProcess; }
public static extern unsafe bool Process32Next( SafeObjectHandle hSnapshot, PROCESSENTRY32* lppe);
public static extern bool Process32First(SafeSnapshotHandle hSnapshot, ref PROCESSENTRY32 lppe);
public static extern int Process32Next(int hSnapshot, [MarshalAs(UnmanagedType.Struct)] ref PROCESSENTRY32 lppe);
private static bool HasParentProcessWindows(int pid) { IntPtr handleToSnapshot = IntPtr.Zero; try { PROCESSENTRY32 procEntry = new PROCESSENTRY32(); procEntry.dwSize = (UInt32)Marshal.SizeOf(typeof(PROCESSENTRY32)); handleToSnapshot = CreateToolhelp32Snapshot(SnapshotFlags.Process, (uint)0); if (Process32First(handleToSnapshot, ref procEntry)) { do { if (pid == procEntry.th32ProcessID) { try { Process parentProc = Process.GetProcessById((int)procEntry.th32ParentProcessID); return true; } catch (ArgumentException) { return false; } } } while (Process32Next(handleToSnapshot, ref procEntry)); } else { Log.Error("Failed to load process infomration with error code {0}.", Marshal.GetLastWin32Error()); } } catch (Exception ex) { Log.Error("Can't get list of processes. Exception: {0}", ex.Message); } finally { // Must clean up the snapshot object! CloseHandle(handleToSnapshot); } return false; }
public static extern Int32 Process32Next(IntPtr hSnapshot, ref PROCESSENTRY32 pe32);
/*public static int GetParentProcessId(uint pid) { PROCESS_BASIC_INFORMATION pbi = new PROCESS_BASIC_INFORMATION(); //Get a handle to our own process IntPtr hProc = OpenProcess((ProcessAccessFlags)0x001F0FFF, false, pid); try { int sizeInfoReturned; int queryStatus = NtQueryInformationProcess(hProc, 0, ref pbi, pbi.Size, out sizeInfoReturned); } finally { if (!hProc.Equals(IntPtr.Zero)) { //Close handle and free allocated memory CloseHandle(hProc); hProc = IntPtr.Zero; } } return (int)pbi.InheritedFromUniqueProcessId; }*/ // get the parent process given a pid public static uint GetParentProcess(uint pid) { uint parentProc = 0; IntPtr handleToSnapshot = IntPtr.Zero; try { PROCESSENTRY32 procEntry = new PROCESSENTRY32(); procEntry.dwSize = (UInt32)Marshal.SizeOf(typeof(PROCESSENTRY32)); handleToSnapshot = CreateToolhelp32Snapshot((uint)SnapshotFlags.Process, 0); if (Process32First(handleToSnapshot, ref procEntry)) { do { if (pid == procEntry.th32ProcessID) { parentProc = procEntry.th32ParentProcessID; break; } } while (Process32Next(handleToSnapshot, ref procEntry)); } else { throw new ApplicationException(string.Format("Failed with win32 error code {0}", Marshal.GetLastWin32Error())); } } catch (Exception ex) { throw new ApplicationException("Can't get the process.", ex); } finally { // Must clean up the snapshot object! CloseHandle(handleToSnapshot); } return parentProc; }
public static extern bool Process32First(IntPtr hSnapshot, ref PROCESSENTRY32 lppe);
public static extern bool Process32Next( IntPtr hSnapshot, ref PROCESSENTRY32 pe32);
internal static extern bool Process32Next(SafeSnapshotHandle hSnapshot, ref PROCESSENTRY32 lppe);
private static extern bool Process32First(IntPtr hSnapshot, ref PROCESSENTRY32 lppe);
static extern bool Process32Next(IntPtr hSnapshot, ref PROCESSENTRY32 lppe);
public static extern bool Process32Next( [In] IntPtr hSnapshot, ref PROCESSENTRY32 lppe );
/// <summary> /// Win32-specific implementation of TerminateChildProcesses /// </summary> /// <param name="RootProcessId">The root process id of the tree to be terminated</param> static void TerminateChildProcessesWin32(int RootProcessId) { Stopwatch Timer = Stopwatch.StartNew(); HashSet <uint> UnableToOpenProcessIds = new HashSet <uint>(); for (; ;) { // Find a map of process id to parent process id Dictionary <uint, uint> ProcessIdToParentProcessId = new Dictionary <uint, uint>(); using (SafeFileHandle SnapshotHandle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)) { if (!SnapshotHandle.IsInvalid) { PROCESSENTRY32 ProcessEntry = new PROCESSENTRY32(); ProcessEntry.dwSize = (uint)Marshal.SizeOf(typeof(PROCESSENTRY32)); for (bool bResult = Process32First(SnapshotHandle, ref ProcessEntry); bResult; bResult = Process32Next(SnapshotHandle, ref ProcessEntry)) { if (ProcessEntry.th32ParentProcessID != 0) { ProcessIdToParentProcessId[ProcessEntry.th32ProcessID] = ProcessEntry.th32ParentProcessID; } } } } // Find any process ids which are a descendant from the root process it List <uint> ChildProcessIds = new List <uint>(); foreach (KeyValuePair <uint, uint> Pair in ProcessIdToParentProcessId) { uint ParentProcessId = Pair.Value; for (; ;) { if (ParentProcessId == RootProcessId) { ChildProcessIds.Add(Pair.Key); break; } if (!ProcessIdToParentProcessId.TryGetValue(ParentProcessId, out ParentProcessId)) { break; } } } // If there's nothing running, we can quit if (ChildProcessIds.Count == 0) { break; } // Check if we need to print a message about what's going on bool bPrintStatus = false; if (Timer == null) { Timer = Stopwatch.StartNew(); bPrintStatus = true; } else if (Timer.Elapsed > TimeSpan.FromSeconds(10.0)) { Timer.Restart(); bPrintStatus = true; } // Try to kill all the child processes bool bWaitingForProcess = false; foreach (uint ChildProcessId in ChildProcessIds) { using (SafeProcessHandle ProcessHandle = OpenProcess(PROCESS_TERMINATE, false, ChildProcessId)) { if (ProcessHandle.IsInvalid) { if (UnableToOpenProcessIds.Add(ChildProcessId)) { bWaitingForProcess = true; } else { Log.TraceWarning("Unable to terminate process {0}.", ChildProcessId); } } else { if (bPrintStatus) { Log.TraceInformation("Waiting for process {0} to terminate.", ChildProcessId); } TerminateProcess(ProcessHandle, 3); bWaitingForProcess = true; } } } // If there wasn't anything we could do, bail out if (!bWaitingForProcess) { break; } // Allow a short amount of time for processes to exit, then check again Thread.Sleep(500); } }