-
Notifications
You must be signed in to change notification settings - Fork 0
/
ProcessCollection.cs
192 lines (171 loc) · 7.53 KB
/
ProcessCollection.cs
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Management;
using System.Globalization;
using System.Threading.Tasks;
using System.Collections.Specialized;
namespace uk.JohnCook.dotnet.NAudioWrapperLibrary
{
public sealed class ProcessCollection : ObservableCollection<ObservableProcess>, IDisposable
{
private readonly SynchronizationContext _Context;
private static readonly Lazy<ProcessCollection> lazySingleton =
new Lazy<ProcessCollection>(
() => new ProcessCollection()
);
private bool disposedValue;
public static ProcessCollection Instance { get { return lazySingleton.Value; } }
public static ObservableCollection<ObservableProcess> Processes { get; } = new ObservableCollection<ObservableProcess>();
private static List<string> ProcessNameList { get; } = new List<string>();
public bool ProcessesAreEnumerated { get; private set; }
private readonly ManagementEventWatcher processCreatedEventWatcher;
private readonly ManagementEventWatcher processDeletedEventWatcher;
private ProcessCollection()
{
_Context = SynchronizationContext.Current;
Processes.CollectionChanged += Processes_CollectionChanged;
processCreatedEventWatcher = WindowsManagementInstrumentation.NewProcessCreatedEventWatcher();
processCreatedEventWatcher.EventArrived += ProcessCreatedEventArrived;
processCreatedEventWatcher.Start();
processDeletedEventWatcher = WindowsManagementInstrumentation.ProcessDestroyedEventWatcher();
processDeletedEventWatcher.EventArrived += ProcessDeletedEventArrived;
processDeletedEventWatcher.Start();
Initialise();
}
private async void Initialise()
{
await Task.Run(
() => EnumerateProcesses()
).ConfigureAwait(true);
}
private Task EnumerateProcesses()
{
foreach (Process process in Process.GetProcesses())
{
ObservableProcess observableProcess = new ObservableProcess(process);
if (!String.IsNullOrEmpty(observableProcess.MainWindowTitle))
{
_Context.Send(
x => Processes.Add(observableProcess),
null);
}
}
ProcessesAreEnumerated = true;
NotifyCollectionEnumerated();
return Task.CompletedTask;
}
public event EventHandler CollectionEnumerated;
public new event NotifyCollectionChangedEventHandler CollectionChanged;
void NotifyCollectionEnumerated()
{
_Context.Send(
x => SortCollection(),
null);
_Context.Send(
x => CollectionEnumerated?.Invoke(this, EventArgs.Empty),
null);
}
void NotifyCollectionChanged(NotifyCollectionChangedEventArgs collectionChangedEventArgs)
{
_Context.Send(
x => Instance.CollectionChanged?.Invoke(this, collectionChangedEventArgs),
null);
}
private void Processes_CollectionChanged(object sender, NotifyCollectionChangedEventArgs collectionChangedEventArgs)
{
NotifyCollectionChanged(collectionChangedEventArgs);
}
private static void SortCollection()
{
ProcessNameList.Clear();
ProcessNameList.AddRange(Processes.Select(x => x.ProcessName).ToList());
ProcessNameList.Sort();
string currentProcessName = String.Empty;
int processNameOccurance = 0;
for (int i = 0; i < ProcessNameList.Count; i++)
{
if (ProcessNameList[i] == currentProcessName)
{
processNameOccurance++;
}
else
{
currentProcessName = ProcessNameList[i];
processNameOccurance = 0;
}
ObservableProcess observableProcess = Processes.Where(x => x.ProcessName == ProcessNameList[i]).ToArray()[processNameOccurance];
Processes.Move(Processes.IndexOf(observableProcess), i);
}
}
public static void ProcessCreatedEventArrived(object sender, EventArrivedEventArgs e)
{
if (e == null) { throw new ArgumentNullException(nameof(e)); }
ManagementBaseObject eventProcess = e.NewEvent["TargetInstance"] as ManagementBaseObject;
string processName = eventProcess.Properties["Name"].Value.ToString();
int processId = int.Parse(eventProcess.Properties["ProcessId"].Value.ToString(), NumberStyles.Integer, CultureInfo.InvariantCulture);
ObservableProcess newProcess = new ObservableProcess(Process.GetProcessById(processId));
if (!String.IsNullOrEmpty(newProcess.MainWindowTitle))
{
Instance._Context.Send(
x => Processes.Add(newProcess),
null);
Instance._Context.Send(
x => SortCollection(),
null);
}
Trace.WriteLine($"A new {processName} process was created with PID {processId}!");
}
public static void ProcessDeletedEventArrived(object sender, EventArrivedEventArgs e)
{
if (e == null) { throw new ArgumentNullException(nameof(e)); }
ManagementBaseObject eventProcess = e.NewEvent["TargetInstance"] as ManagementBaseObject;
string processName = eventProcess.Properties["Name"].Value.ToString();
int processId = int.Parse(eventProcess.Properties["ProcessId"].Value.ToString(), NumberStyles.Integer, CultureInfo.InvariantCulture);
ObservableProcess deletedProcess = Processes.FirstOrDefault(x => x.Id == processId);
if (deletedProcess != default)
{
Instance._Context.Send(
x => Processes.Remove(deletedProcess),
null);
Instance._Context.Send(
x => SortCollection(),
null);
}
Trace.WriteLine($"Process {processName} with PID {processId} has been destroyed!");
}
#region dispose
private void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
// TODO: dispose managed state (managed objects)
processCreatedEventWatcher.Dispose();
processDeletedEventWatcher.Dispose();
}
// TODO: free unmanaged resources (unmanaged objects) and override finalizer
// TODO: set large fields to null
disposedValue = true;
}
}
// // TODO: override finalizer only if 'Dispose(bool disposing)' has code to free unmanaged resources
~ProcessCollection()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: false);
}
public void Dispose()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
#endregion
}
}