Beispiel #1
0
        /// <summary>Iterates all processes in Windows, running the given function.  This is based on processes, NOT windows.  Some may be hidden/background</summary>
        public static void IterateRunningProcesses(ProcessFunction procFunction)
        {
            Windows.PROCESSENTRY32 pe32 = new Windows.PROCESSENTRY32();
            //  Take a snapshot of all processes in the system.
            var hProcessSnap = Windows.CreateToolhelp32Snapshot(Windows.SnapshotFlags.Process, 0);

            if (hProcessSnap.IsInvalid())
            {
                return;
            }

            //  Fill in the size of the structure before using it.
            pe32.dwSize = (uint)Marshal.SizeOf(typeof(Windows.PROCESSENTRY32));
            //  Walk the snapshot of the processes, and for each process, display information.
            if (Windows.Process32First(hProcessSnap, ref pe32))
            {
                do
                {
                    int           nLength = 1024;
                    StringBuilder szPath  = new StringBuilder(nLength);
                    // requires Vista or later:  (we no longer have the fall back that was in SAW6)
                    IntPtr hProcess = Windows.OpenProcess(Windows.ProcessAccessFlags.QueryLimitedInformation, false, (int)pe32.th32ProcessID);
                    if (!hProcess.IsZero())                     // will fail for a few (eg System process is protected), but they're not going to be the process we're looking for.
                    {
                        if (Windows.QueryFullProcessImageName(hProcess, 0, szPath, ref nLength))
                        {
                            if (!procFunction(pe32, szPath.ToString(0, nLength)))
                            {
                                Windows.CloseHandle(hProcessSnap);
                                Windows.CloseHandle(hProcess);
                                return;
                            }
                        }
                        Windows.CloseHandle(hProcess);
                    }
                } while (Windows.Process32Next(hProcessSnap, ref pe32));
            }
            Windows.CloseHandle(hProcessSnap);
        }