-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathEnumerate Window Processes
87 lines (67 loc) · 2.78 KB
/
Enumerate Window Processes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
/*
* Use the Windows API functions EnumWindows and GetWindowThreadProcessId to list all of the Window processes on your desktop.
Hint: To get the address of a method (the first argument to EnumWindows), you’ll need to define a delegate with the appropriate signature.
If you are writing in Visual Basic, you will also need to use the Address Of operator.
Hint: Once you have the process id, use Process.GetProcessById to retrieve the needed process information.
As for the ListProcesses exercise, write the application to output each unique window/process name and the number of instances running.
Order the output by the # running processes, descending.
A delegate is a reference type variable that holds the reference to a method. Here it's GetProcesses(). Here runningProcs can be a delegate.
*/
namespace ListDesktopWindowProcesses
{
class Program
{
public delegate bool myDelegate(int hwnd, int lParam);
static void Main(string[] args)
{
myDelegate myDelegate = new myDelegate(Objects.Window);
Objects.EnumWindows(myDelegate, 0);
Objects.PrintDict();
Console.Read();
}
public class Objects
{
[DllImport("user32.dll")]
public static extern int EnumWindows(myDelegate cakkPtr, int lPar);
[DllImport("user32.dll", SetLastError = true)]
static extern uint GetWindowThreadProcessId(int hWnd, out int lpdwProcessId);
public static Process GetWindowThreadProcess(int hwnd)
{
int processID;
GetWindowThreadProcessId(hwnd, out processID);
try
{
return Process.GetProcessById(processID);
}
catch (ArgumentNullException)
{
return null;
}
}
static Dictionary<string, int> myDictionary = new Dictionary<string, int>();
public static bool Window(int hwnd, int lParam)
{
String pName = GetWindowThreadProcess(hwnd).ProcessName;
if (myDictionary.ContainsKey(pName))
{
myDictionary[pName]++;
}
else
{
myDictionary.Add(pName, 1);
}
return true;
}
public static void PrintDict()
{
foreach (KeyValuePair<string, int> kvp in myDictionary.OrderByDescending(k => k.Value))
Console.WriteLine($"{kvp.Key}:{kvp.Value}");
}
}
}
}