Baacus
Baacus

Reputation: 21

How to get cpu and memory usage of process just same as Task Manager on Windows 10?

I want to get cpu and memory usage of processes which are shown in Task Manager. I tried wmi, performancecounter but none of them shows the same values on Task Manager.

EDIT: I do not want to get total cpu and memory usage of pc which is answered on other questions. I want to get these values per each app group in Task Manager.

Task Manager on Windows 10 groups processes by its Application name. For example, Skype has some services which are running on the background and they are shown as grouped by "Skype" name and Task Manager shows total cpu and memory usage of these processes.

Task Manager Screenshot

I tried to search for properties of processes by using Process.GetProcesses() but I couldn't find any common property for these processes.

In shortly, how do I group processes just like Task Manager on Windows 10 and calculate cpu and memory usage values just same values on Task Manager in C#?

In other words, how do I copy a table of current processes just same as Task Manager on Windows 10?



        public class CPU_Memory_Calculator
        {
            private double _percentCPU = 0, _memoryMB = 0;

            public double GetPercentCPU { get { return _percentCPU; } }
            public double GetMemoryMB { get { return _memoryMB; } }

            public CPU_Memory_Calculator(string processName)
            {
                Process[] processArray = Process.GetProcesses().Where(x => x.ProcessName.ToLower().Contains(processName.ToLower())).ToArray();
                if (processArray.Length >= 0)
                {
                    double totalMemory = 0;

                    using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2",
                                "SELECT * FROM Win32_PerfFormattedData_PerfProc_Process WHERE Name LIKE '%" + processName + "%'"))
                    {
                        foreach (ManagementObject obj in searcher.Get())
                        {
                            double memory = Convert.ToDouble(obj["WorkingSet"]) / 1024.0 / 1024.0;
                            totalMemory += memory;
                        }
                    }

                    _memoryMB = Math.Round(totalMemory, 2);
                }

            }
        }

Upvotes: 0

Views: 1036

Answers (0)

Related Questions