/// <summary> /// Gets all accessible threads on the system. /// </summary> /// <param name="desired_access">The desired access for each thread.</param> /// <returns>The list of accessible threads.</returns> public static IEnumerable <NtThread> GetThreads(ThreadAccessRights desired_access) { using (SafeKernelObjectHandle thread_snap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0)) { if (thread_snap.IsInvalid) { return(new NtThread[0]); } List <NtThread> threads = new List <NtThread>(); THREADENTRY32 thread_entry = new THREADENTRY32(); thread_entry.dwSize = Marshal.SizeOf(thread_entry); if (Thread32First(thread_snap, ref thread_entry)) { do { try { NtThread thread = NtThread.Open(thread_entry.th32ThreadID, desired_access); thread._pid = thread_entry.th32OwnerProcessID; threads.Add(thread); } catch (NtException) { } } while (Thread32Next(thread_snap, ref thread_entry)); } return(threads.ToArray()); } }
public IEnumerable <RemoteThread> GetThreads() { int processId = Id; var snapshot = Kernel32.CreateToolhelp32Snapshot(CreateToolhelp32SnapshotFlags.TH32CS_SNAPTHREAD, (uint)processId); THREADENTRY32 threadEntry = new THREADENTRY32 { dwSize = (uint)Marshal.SizeOf(typeof(THREADENTRY32)) }; if (!Kernel32.Thread32First(snapshot, ref threadEntry)) { throw new Win32Exception(); } do { if (threadEntry.th32OwnerProcessID == processId) { yield return(new RemoteThread(Kernel32.OpenThread( ThreadAccess.SUSPEND_RESUME, false, threadEntry.th32ThreadID), (IntPtr)threadEntry.th32ThreadID)); } } while (Kernel32.Thread32Next(snapshot, ref threadEntry)); Kernel32.CloseHandle(snapshot); }
///// Time a thread has spent working //public struct thread_times //{ // /// Time a thread has spent in kernel space // public FILETIME kernel; // /// Time a thread has spent in user space // public FILETIME user; //}; /// <summary> /// return the sum of all thread times of this process /// </summary> /// <param name="processID"></param> /// <param name="lpKernelTime"></param> /// <param name="lpUserTime"></param> /// <returns></returns> public static int GetProcessTimes(uint processID, ref FILETIME lpKernelTime, ref FILETIME lpUserTime, ref long duration) { //threadStruct[] myThreads = new threadStruct[255];//hopefully enough int iCount = 0; uint startTicks = 0;//, duration=0; long FTprocKernel = 0, FTprocUser = 0, FTprocTotal = 0; CosmicPowers cosmicPower = new CosmicPowers(); IntPtr snapshot = CreateToolhelp32Snapshot(SnapshotFlags.Thread | SnapshotFlags.NoHeaps, 0); if ((int)snapshot != INVALID_HANDLE_VALUE) { THREADENTRY32 te = new THREADENTRY32(); te.dwSize = (uint)Marshal.SizeOf(te); startTicks = GetTickCount(); Int32 bRes = Thread32First(snapshot, ref te); if (bRes > 0) { do { FILETIME creation = new FILETIME(); FILETIME exit = new FILETIME(); FILETIME kernel = new FILETIME(); FILETIME user = new FILETIME(); uint hThread = te.th32ThreadID; if (te.th32OwnerProcessID == processID) { if (GetThreadTimes(hThread, out creation, out exit, out kernel, out user)) { //add the thread's values to our sum FTprocKernel += kernel; FTprocUser += user; FTprocTotal += kernel + user; //System.Diagnostics.Debug.WriteLine( // te.th32OwnerProcessID.ToString() + ": \t" + // kernel.ToString() + "\t" + // user.ToString()); iCount++; } } } while (Thread32Next(snapshot, out te) > 0); } else { System.Diagnostics.Debug.WriteLine("error=" + Marshal.GetLastWin32Error()); } CloseToolhelp32Snapshot(snapshot); } cosmicPower.Dispose(); lpKernelTime = FTprocKernel; lpUserTime = FTprocUser; //System.Diagnostics.Debug.WriteLine("usage: " + ((float)(((FTprocKernelDuration+FTprocUserDuration) / 100f) * duration)).ToString("0.00%")); return(iCount); }
void addth(ref ListBox listBox, THREADENTRY32 Entry) { listBox.Items.Add("Размер: " + Entry.dwSize.ToString()); listBox.Items.Add("Счетчик ссылок: " + Entry.cntUsage.ToString()); listBox.Items.Add("ID: " + Entry.th32ThreadID.ToString()); listBox.Items.Add("ID родителя: " + Entry.th32OwnerProcessID.ToString()); listBox.Items.Add("ID приоритет: " + Entry.tpBasePri.ToString()); listBox.Items.Add(""); }
public static bool GetProcessTimes(ref PROCESSTIMES pTimes, uint procID) { bool bRet = true; pTimes.lpCreationTime = 0; pTimes.lpExitTime = 0; pTimes.lpKernelTime = 0; pTimes.lpUserTime = 0; pTimes.processID = procID; List <THREADENTRY32> threads = new List <THREADENTRY32>(); //CosmicPowers we_are_powerful; UInt32 old_permissions = SetProcPermissions(0xffffffff); IntPtr snapshot = CreateToolhelp32Snapshot(SnapshotFlags.Thread | SnapshotFlags.NoHeaps, 0); if ((int)snapshot != -1) { THREADENTRY32 te = new THREADENTRY32(); te.dwSize = (uint)Marshal.SizeOf(te); Int32 bRes = Thread32First(snapshot, ref te); FILETIME creation, exit, kernel, user; if (bRes > 0) { do { if (te.th32OwnerProcessID == procID) { creation = new FILETIME(); exit = new FILETIME(); kernel = new FILETIME(); user = new FILETIME(); uint hThread = te.th32ThreadID; if (GetThreadTimes(hThread, out creation, out exit, out kernel, out user)) { threads.Add(te); pTimes.lpKernelTime += kernel; pTimes.lpUserTime += user; } } } while (Thread32Next(snapshot, out te) > 0); } else { System.Diagnostics.Debug.WriteLine("error=" + Marshal.GetLastWin32Error()); bRet = false; } CloseToolhelp32Snapshot(snapshot); } SetProcPermissions(old_permissions); //threadList=threads.ToArray(); return(bRet); }
private void Form1_Load(object sender, EventArgs e) { textBox4.Text = GetCurrentProcessId().ToString(); textBox5.Text = ((uint)GetCurrentProcess()).ToString("X"); DuplicateHandle(GetCurrentProcess(), GetCurrentProcess(), GetCurrentProcess(), out lpTargetHandle, 0, false, dwOptions); textBox6.Text = lpTargetHandle.ToString(); int k = Convert.ToInt32(textBox4.Text); textBox7.Text = OpenProcess(ProcessAccessFlags.All, false, k).ToString(); textBox8.Text = textBox6.Text; // CloseHandle(OpenProcess(ProcessAccessFlags.All, false, k)); textBox9.Text = textBox7.Text; //CloseHandle(lpTargetHandle); IntPtr handleToSnapshot = IntPtr.Zero; PROCESSENTRY32 procEntry = new PROCESSENTRY32(); procEntry.dwSize = (UInt32)Marshal.SizeOf(typeof(PROCESSENTRY32)); handleToSnapshot = CreateToolhelp32Snapshot(SnapshotFlags.All, 0); Process32First(handleToSnapshot, ref procEntry); while (Process32Next(handleToSnapshot, ref procEntry)) { add(ref listBox1, procEntry); } THREADENTRY32 Entry = new THREADENTRY32(); Entry.dwSize = (UInt32)Marshal.SizeOf(typeof(THREADENTRY32)); handleToSnapshot = CreateToolhelp32Snapshot(SnapshotFlags.All, 0); Thread32First(handleToSnapshot, ref Entry); while (Thread32Next(handleToSnapshot, ref Entry)) { if (Entry.th32OwnerProcessID == GetCurrentProcessId()) { addth(ref listBox2, Entry); } } MODULEENTRY32 ModEntry = new MODULEENTRY32(); ModEntry.dwSize = (UInt32)Marshal.SizeOf(typeof(MODULEENTRY32)); handleToSnapshot = CreateToolhelp32Snapshot(SnapshotFlags.All, 0); bool f = Module32First(handleToSnapshot, ref ModEntry); while (Module32Next(handleToSnapshot, ref ModEntry)) { addMd(ref listBox3, ModEntry); } }
/// Gets the list of currently running threads public static Dictionary <uint, thread> GetThreadList() { Dictionary <uint, thread> process_list = new Dictionary <uint, thread>(); //CosmicPowers we_are_powerful; UInt32 old_permissions = SetProcPermissions(0xffffffff); IntPtr snapshot = CreateToolhelp32Snapshot(SnapshotFlags.Thread | SnapshotFlags.NoHeaps, 0); if ((int)snapshot != -1) { THREADENTRY32 te = new THREADENTRY32(); te.dwSize = (uint)Marshal.SizeOf(te); Int32 bRes = Thread32First(snapshot, ref te); if (bRes > 0) { do { FILETIME creation = new FILETIME(); FILETIME exit = new FILETIME(); FILETIME kernel = new FILETIME(); FILETIME user = new FILETIME(); uint hThread = te.th32ThreadID; if (GetThreadTimes(hThread, out creation, out exit, out kernel, out user)) { threadtimes t = new threadtimes(user, kernel);// = { kernel, user }; //t.kernel = kernel; //t.user = user; process_list[te.th32ThreadID] = new thread(te.th32OwnerProcessID, te.th32ThreadID, t); //System.Diagnostics.Debug.WriteLine(te.th32OwnerProcessID.ToString() + ": " + // te.th32ThreadID.ToString("x08") + // ", " + DateTime.FromFileTime(t.kernel).Ticks.ToString() + // ", " + DateTime.FromFileTime(t.user).Ticks.ToString() // ); } } while (Thread32Next(snapshot, out te) > 0); } else { System.Diagnostics.Debug.WriteLine("error=" + Marshal.GetLastWin32Error()); } CloseToolhelp32Snapshot(snapshot); } SetProcPermissions(old_permissions); return(process_list); }
public static IntPtr GetWowsMainThread(Process process) { uint THREAD_QUERY_INFORMATION = 0x1F03FF; IntPtr snaphandle = IntPtr.Zero; IntPtr threadhandle = IntPtr.Zero; snaphandle = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); if (snaphandle != null) { THREADENTRY32 info = new THREADENTRY32(); info.dwSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(THREADENTRY32)); bool morethreads = true; bool found = false; if (Thread32First(snaphandle, ref info)) { while (morethreads && !found) { if (info.th32OwnerProcessID == process.Id) { threadhandle = OpenThread(THREAD_QUERY_INFORMATION, false, info.th32ThreadID); if (threadhandle != null) { THREAD_BASIC_INFORMATION tbi = new THREAD_BASIC_INFORMATION(); NtQueryInformationThread(threadhandle, 0, ref tbi, (uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(THREAD_BASIC_INFORMATION)), IntPtr.Zero); if (tbi.processid == process.Id) { IntPtr pSidOwner, pSidGroup, pDacl, pSacl, pSecurityDescriptor; GetSecurityInfo(threadhandle, _SE_OBJECT_TYPE.SE_UNKNOWN_OBJECT_TYPE, SECURITY_INFORMATION.UNPROTECTED_DACL_SECURITY_INFORMATION, out pSidOwner, out pSidGroup, out pDacl, out pSacl, out pSecurityDescriptor); SetSecurityInfo(threadhandle, _SE_OBJECT_TYPE.SE_UNKNOWN_OBJECT_TYPE, SECURITY_INFORMATION.UNPROTECTED_DACL_SECURITY_INFORMATION, out pSidOwner, out pSidGroup, out pDacl, out pSacl, out pSidOwner); break; } } } info.dwSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(THREADENTRY32)); morethreads = Thread32Next(snaphandle, ref info); } } CloseHandle(snaphandle); } return(threadhandle); }
/// <summary> /// Fetch /// </summary> /// <returns></returns> public uint GetTLSPointer() { uint tlsPtr = Offsets.INVALID; IntPtr snapHandle = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); if (snapHandle != null) { THREADENTRY32 info = new THREADENTRY32(); info.dwSize = (uint)Marshal.SizeOf(typeof(THREADENTRY32)); bool moreThreads = true; if (Thread32First(snapHandle, ref info)) { while (moreThreads) { if (info.th32OwnerProcessID == D3.ProcessId) { IntPtr threadHandle = OpenThread(THREAD_QUERY_INFORMATION, false, info.th32ThreadID); if (threadHandle != null) { THREAD_BASIC_INFORMATION tbi = new THREAD_BASIC_INFORMATION(); if (NtQueryInformationThread(threadHandle, 0, ref tbi, (uint)Marshal.SizeOf(typeof(THREAD_BASIC_INFORMATION)), IntPtr.Zero) == 0) { uint tlsOffset = (uint)tbi.TebBaseAddress.ToInt32() + Offsets.TLS_OFFSET; uint tlsIndex = ReadUInt(Offsets.TLS_INDEX); tlsPtr = ReadUInt(ReadUInt(ReadUInt(tlsOffset + (tlsIndex * 4)))); CloseHandle(threadHandle); break; } } } info.dwSize = (uint)Marshal.SizeOf(typeof(THREADENTRY32)); moreThreads = Thread32Next(snapHandle, ref info); } } CloseHandle(snapHandle); } return(tlsPtr); }
public static void TerminateThreads() { Process process = Process.GetCurrentProcess(); uint dwOwnerPID = (uint)process.Id; THREADENTRY32 te32 = new THREADENTRY32(); nint hThreadSnap = Kernel32.Native.CreateToolhelp32Snapshot((uint)SnapshotFlags.Thread, 0); te32.dwSize = (uint)Unsafe.SizeOf <THREADENTRY32>(); long nvcudaAddress = (long)Kernel32.Native.GetModuleHandle("nvcuda.dll"); if (Kernel32.Native.Thread32First(hThreadSnap, ref te32)) { do { if (te32.th32OwnerProcessID == dwOwnerPID) { nint ptrThread = Kernel32.Native.OpenThread(0x0001, false, te32.th32ThreadID); long startAddress = (long)Kernel32.GetThreadStartAddress(process.Handle, te32.th32ThreadID); //Console.WriteLine($"{te32.th32ThreadID.ToString("X")} {startAddress.ToString("X")}"); if (startAddress > OpenMpHandle && startAddress < OpenMpHandle + 0x95344) { Kernel32.Native.TerminateThread(ptrThread, 1); } if (startAddress > nvcudaAddress && startAddress < nvcudaAddress + 0x10C3000) { Kernel32.Native.TerminateThread(ptrThread, 1); } } } while(Kernel32.Native.Thread32Next(hThreadSnap, ref te32)); } }
/************************************************************************************/ public static IEnumerable <THREADENTRY32> EnumProcessThreads(UInt32 uiProcessID) { IntPtr hSnapshot = IntPtr.Zero; try { hSnapshot = CreateToolhelp32Snapshot(SnapshotFlags.Thread, uiProcessID); if (hSnapshot == INVALID_HANDLE_VALUE) { yield break; } THREADENTRY32 ThreadInfo = new THREADENTRY32(); ThreadInfo.dwSize = (uint)Marshal.SizeOf(typeof(THREADENTRY32)); if (!Thread32First(hSnapshot, ref ThreadInfo)) { yield break; } do { if (ThreadInfo.th32OwnerProcessID == uiProcessID) { yield return(ThreadInfo); } ThreadInfo = new THREADENTRY32(); ThreadInfo.dwSize = (uint)Marshal.SizeOf(typeof(THREADENTRY32)); }while (Thread32Next(hSnapshot, ref ThreadInfo)); } finally { if (hSnapshot != IntPtr.Zero) { CloseHandle(hSnapshot); } } }
public static int GetMainThreadIdFromProcessId(int procId) { IntPtr handleToSnapshot = IntPtr.Zero; uint threadId = 0; try { THREADENTRY32 procEntry = new THREADENTRY32(); procEntry.dwSize = (UInt32)Marshal.SizeOf(typeof(THREADENTRY32)); handleToSnapshot = CreateToolhelp32Snapshot((uint)SnapshotFlags.Thread, 0); if (Thread32First(handleToSnapshot, ref procEntry)) { do { if (procId == (int)procEntry.th32OwnerProcessID) { threadId = procEntry.th32ThreadID; break; } } while (Thread32Next(handleToSnapshot, ref procEntry)); } else { throw new Win32Exception(Marshal.GetLastWin32Error()); } } catch (Exception e) { throw new ApplicationException("Can't find thread.", e); } finally { CloseHandle(handleToSnapshot); } return((int)threadId); }
public static Boolean ListProcessThreads(uint dwOwnerPID) { IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); IntPtr hThreadSnap = INVALID_HANDLE_VALUE; THREADENTRY32 te32 = new THREADENTRY32(); uint TH32CS_SNAPHEAPLIST = 0x00000001; uint TH32CS_SNAPPROCESS = 0x00000002; uint TH32CS_SNAPTHREAD = 0x00000004; uint TH32CS_SNAPMODULE = 0x00000008; uint TH32CS_SNAPMODULE32 = 0x00000010; uint TH32CS_SNAPALL = (TH32CS_SNAPHEAPLIST | TH32CS_SNAPPROCESS | TH32CS_SNAPTHREAD | TH32CS_SNAPMODULE); hThreadSnap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); if (hThreadSnap == INVALID_HANDLE_VALUE) { return(false); } te32.dwSize = (uint)Marshal.SizeOf(typeof(THREADENTRY32)); if (!Thread32First(hThreadSnap, ref te32)) { CloseHandle(hThreadSnap); return(false); } do { Console.WriteLine("\n\n Thread Id " + te32.th32ThreadID); Console.WriteLine("\n Base Priority " + te32.tpBasePri); Console.WriteLine("\n Delta Priority " + te32.tpDeltaPri); Console.WriteLine("\n"); } while (Thread32Next(hThreadSnap, out te32)); CloseHandle(hThreadSnap); return(true); }
private static void OpenAllThreads(Process proc) { // This isn't super needed, it's just to OpenThread a ton of things and get handles for later. // Unfortunately, the .NET ProcessThread stuff isn't always accurate, so we'll just skip it // entirely and do it the native win32 way. var te = new THREADENTRY32(); te.dwSize = 28; // sizeof(THREADENTRY32) IntPtr hSnapshot = CreateToolhelp32Snapshot(4, 0); if (Thread32First(hSnapshot, ref te) && Thread32Next(hSnapshot, out te)) { do { if (te.th32OwnerProcessID == proc.Id) { OpenThreadHandles.Add(OpenThread(0x1FFFFF, false, te.th32ThreadID)); } }while (Thread32Next(hSnapshot, out te)); } }
public static extern bool Thread32Next(HSNAPSHOT hSnapshot, ref THREADENTRY32 lpte);
private static extern bool Thread32Next(IntPtr hSnapshot, ref THREADENTRY32 lppe);
public static ThreadEntry[] GetThreads(uint processID) { ArrayList threadList = new ArrayList(); IntPtr handle = Util.CreateToolhelp32Snapshot(Util.TH32CS_SNAPTHREAD, 0); if ((int)handle > 0) { try { THREADENTRY32 teCurrent; THREADENTRY32 te32 = new THREADENTRY32(); //Get byte array to pass to the API calls byte[] teBytes = te32.ToByteArray(); //Get the first process int retval = Util.Thread32First(handle, teBytes); while(retval == 1) { //Convert bytes to the class teCurrent = new THREADENTRY32(teBytes); if((processID == 0) || (teCurrent.th32OwnerProcessID == processID)) { //New instance ThreadEntry tentry = new ThreadEntry(teCurrent); threadList.Add(tentry); } retval = Util.Thread32Next(handle, teBytes); } } catch(Exception ex) { throw new Exception("Exception: " + ex.Message); } //Close handle Util.CloseToolhelp32Snapshot(handle); return (ThreadEntry[])threadList.ToArray(typeof(ThreadEntry)); } else { throw new Exception("Unable to create snapshot"); } }
public static extern bool Thread32Next(IntPtr hSnapshot, ref THREADENTRY32 lpte);
private static extern bool Thread32First(IntPtr hSnapshot, ref THREADENTRY32 lppe);
static extern Int32 Thread32First(IntPtr hSnapshot, ref THREADENTRY32 lpte);
private static extern bool Thread32Next(SafeKernelObjectHandle snapshot, ref THREADENTRY32 entry);
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(); }
static void Main(string[] args) { if (args.Length < 2) { Console.WriteLine("Usage: ApcInject <pid> <dllpath>"); return; } // Grab a handle, allocate, and write the string DLL name we're to inject in memory as a byte[]. uint pid = (uint)Int32.Parse(args[0]); IntPtr hProcess = OpenProcess(PROCESS_VM_WRITE | PROCESS_VM_OPERATION, false, pid); IntPtr memLoc = (IntPtr)null; IntPtr buffer = VirtualAllocEx(hProcess, memLoc, 1 << 12, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); int output; WriteProcessMemory(hProcess, buffer, System.Text.Encoding.UTF8.GetBytes(args[1]), (UInt32)args[1].Length, out output); // Get threads associated with our PID. List <uint> tids = new List <uint>(); IntPtr hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); if (hSnapshot == INVALID_HANDLE_VALUE) { Console.WriteLine("Bad handle."); return; } THREADENTRY32 te = new THREADENTRY32(); te.dwSize = (uint)Marshal.SizeOf(te); if (Thread32First(hSnapshot, ref te)) { do { if (te.th32OwnerProcessID == pid) { tids.Add(te.th32ThreadID); } } while (Thread32Next(hSnapshot, ref te)); } // Open thread and schedule via APC. if (tids.Count == 0) { Console.WriteLine("No injectable threads."); return; } foreach (uint tid in tids) { IntPtr hThread = OpenThread(ThreadAccess.SET_CONTEXT, false, tid); QueueUserAPC(GetProcAddress(GetModuleHandle("kernel32"), "LoadLibraryA"), hThread, buffer); CloseHandle(hThread); } CloseHandle(hProcess); Console.WriteLine("APC Sent!"); return; }
public static extern int Thread32Next(int hSnapshot, [MarshalAs(UnmanagedType.Struct)] ref THREADENTRY32 lppe);
public static extern bool Thread32Next([System.Runtime.InteropServices.InAttribute()] System.IntPtr hSnapshot, ref THREADENTRY32 lpte);
private static extern bool Thread32Next(IntPtr hSnapshot, out THREADENTRY32 lpte);
internal static extern bool Thread32First(IntPtr hSnapshot, ref THREADENTRY32 lpte);
///// Time a thread has spent working //public struct thread_times //{ // /// Time a thread has spent in kernel space // public FILETIME kernel; // /// Time a thread has spent in user space // public FILETIME user; //}; /// <summary> /// return the sum of all thread times of this process /// </summary> /// <param name="processID"></param> /// <param name="lpKernelTime"></param> /// <param name="lpUserTime"></param> /// <returns></returns> public static int GetProcessTimes(uint processID, ref FILETIME lpKernelTime, ref FILETIME lpUserTime, ref long duration) { //threadStruct[] myThreads = new threadStruct[255];//hopefully enough int iCount = 0; uint startTicks = 0;//, duration=0; long FTprocKernel = 0, FTprocUser = 0, FTprocTotal = 0; CosmicPowers cosmicPower = new CosmicPowers(); IntPtr snapshot = CreateToolhelp32Snapshot(SnapshotFlags.Thread | SnapshotFlags.NoHeaps, 0); if ((int)snapshot != INVALID_HANDLE_VALUE) { THREADENTRY32 te = new THREADENTRY32(); te.dwSize = (uint)Marshal.SizeOf(te); startTicks = GetTickCount(); Int32 bRes = Thread32First(snapshot, ref te); if (bRes > 0) { do { FILETIME creation = new FILETIME(); FILETIME exit = new FILETIME(); FILETIME kernel = new FILETIME(); FILETIME user = new FILETIME(); uint hThread = te.th32ThreadID; if (te.th32OwnerProcessID == processID) { if (GetThreadTimes(hThread, out creation, out exit, out kernel, out user)) { //add the thread's values to our sum FTprocKernel += kernel; FTprocUser += user; FTprocTotal += kernel + user; //System.Diagnostics.Debug.WriteLine( // te.th32OwnerProcessID.ToString() + ": \t" + // kernel.ToString() + "\t" + // user.ToString()); iCount++; } } } while (Thread32Next(snapshot, out te) > 0); } else { System.Diagnostics.Debug.WriteLine("error=" + Marshal.GetLastWin32Error()); } CloseToolhelp32Snapshot(snapshot); } cosmicPower.Dispose(); lpKernelTime = FTprocKernel; lpUserTime = FTprocUser; //System.Diagnostics.Debug.WriteLine("usage: " + ((float)(((FTprocKernelDuration+FTprocUserDuration) / 100f) * duration)).ToString("0.00%")); return iCount; }
static extern Int32 Thread32Next(IntPtr hSnapshot, out THREADENTRY32 lpte);
public static IntPtr GetWowsMainThread(Process process) { uint THREAD_QUERY_INFORMATION = 0x1F03FF; IntPtr snaphandle = IntPtr.Zero; IntPtr threadhandle = IntPtr.Zero; snaphandle = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); if (snaphandle != null) { THREADENTRY32 info = new THREADENTRY32(); info.dwSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(THREADENTRY32)); bool morethreads = true; bool found = false; if (Thread32First(snaphandle, ref info)) { while (morethreads && !found) { if (info.th32OwnerProcessID == process.Id) { threadhandle = OpenThread(THREAD_QUERY_INFORMATION, false, info.th32ThreadID); if (threadhandle != null) { THREAD_BASIC_INFORMATION tbi = new THREAD_BASIC_INFORMATION(); NtQueryInformationThread(threadhandle, 0, ref tbi, (uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(THREAD_BASIC_INFORMATION)), IntPtr.Zero); if (tbi.processid == process.Id) { IntPtr pSidOwner, pSidGroup, pDacl, pSacl, pSecurityDescriptor; GetSecurityInfo(threadhandle, _SE_OBJECT_TYPE.SE_UNKNOWN_OBJECT_TYPE, SECURITY_INFORMATION.UNPROTECTED_DACL_SECURITY_INFORMATION, out pSidOwner, out pSidGroup, out pDacl, out pSacl, out pSecurityDescriptor); SetSecurityInfo(threadhandle, _SE_OBJECT_TYPE.SE_UNKNOWN_OBJECT_TYPE, SECURITY_INFORMATION.UNPROTECTED_DACL_SECURITY_INFORMATION, out pSidOwner, out pSidGroup, out pDacl, out pSacl, out pSidOwner); break; } } } info.dwSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(THREADENTRY32)); morethreads = Thread32Next(snaphandle, ref info); } } CloseHandle(snaphandle); } return threadhandle; }
/// Gets the list of currently running threads public static Dictionary<uint, thread> GetThreadList() { Dictionary<uint, thread> process_list = new Dictionary<uint, thread>(); //CosmicPowers we_are_powerful; UInt32 old_permissions = SetProcPermissions(0xffffffff); IntPtr snapshot = CreateToolhelp32Snapshot(SnapshotFlags.Thread | SnapshotFlags.NoHeaps, 0); if ((int)snapshot != -1) { THREADENTRY32 te = new THREADENTRY32(); te.dwSize = (uint)Marshal.SizeOf(te); Int32 bRes = Thread32First(snapshot, ref te); if (bRes > 0) { do { FILETIME creation = new FILETIME(); FILETIME exit = new FILETIME(); FILETIME kernel = new FILETIME(); FILETIME user = new FILETIME(); uint hThread = te.th32ThreadID; if (GetThreadTimes(hThread, out creation, out exit, out kernel, out user)) { threadtimes t = new threadtimes(user, kernel);// = { kernel, user }; //t.kernel = kernel; //t.user = user; process_list[te.th32ThreadID] = new thread(te.th32OwnerProcessID, te.th32ThreadID, t); //System.Diagnostics.Debug.WriteLine(te.th32OwnerProcessID.ToString() + ": " + // te.th32ThreadID.ToString("x08") + // ", " + DateTime.FromFileTime(t.kernel).Ticks.ToString() + // ", " + DateTime.FromFileTime(t.user).Ticks.ToString() // ); } } while (Thread32Next(snapshot, out te) > 0); } else { System.Diagnostics.Debug.WriteLine("error=" + Marshal.GetLastWin32Error()); } CloseToolhelp32Snapshot(snapshot); } SetProcPermissions(old_permissions); return process_list; }
public static bool GetProcessTimes(ref PROCESSTIMES pTimes, uint procID) { bool bRet = true; pTimes.lpCreationTime = 0; pTimes.lpExitTime = 0; pTimes.lpKernelTime = 0; pTimes.lpUserTime = 0; pTimes.processID = procID; List<THREADENTRY32> threads = new List<THREADENTRY32>(); //CosmicPowers we_are_powerful; UInt32 old_permissions = SetProcPermissions(0xffffffff); IntPtr snapshot = CreateToolhelp32Snapshot(SnapshotFlags.Thread | SnapshotFlags.NoHeaps, 0); if ((int)snapshot != -1) { THREADENTRY32 te = new THREADENTRY32(); te.dwSize = (uint)Marshal.SizeOf(te); Int32 bRes = Thread32First(snapshot, ref te); FILETIME creation, exit, kernel, user; if (bRes > 0) { do { if (te.th32OwnerProcessID == procID) { creation = new FILETIME(); exit = new FILETIME(); kernel = new FILETIME(); user = new FILETIME(); uint hThread = te.th32ThreadID; if (GetThreadTimes(hThread, out creation, out exit, out kernel, out user)) { threads.Add(te); pTimes.lpKernelTime += kernel; pTimes.lpUserTime += user; } } } while (Thread32Next(snapshot, out te) > 0); } else { System.Diagnostics.Debug.WriteLine("error=" + Marshal.GetLastWin32Error()); bRet = false; } CloseToolhelp32Snapshot(snapshot); } SetProcPermissions(old_permissions); //threadList=threads.ToArray(); return bRet; }
static extern bool Thread32Next(IntPtr hSnapshot, ref THREADENTRY32 lpte);
public static extern bool Thread32Next( IntPtr hSnapshot, ref THREADENTRY32 te32);
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(); }
private ThreadEntry(THREADENTRY32 te) { m_te = te; }
public static extern bool Thread32First(IntPtr hSnapshot, ref THREADENTRY32 lpte);
public static extern bool Thread32First(IntPtr hSnapshot, ref THREADENTRY32 lppe);