Repository navigation
Expand file tree
/
Copy pathProcessHelper.cs
More file actions
312 lines (273 loc) · 12.5 KB
/
Copy pathProcessHelper.cs
File metadata and controls
312 lines (273 loc) · 12.5 KB
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
using System;
using System.Collections.Generic;
using System.Linq;
using Process.NET.Extensions;
using Process.NET.Native;
using Process.NET.Native.Types;
using _Process = System.Diagnostics.Process;
namespace Process.NET.Utilities
{
public static class ProcessHelper
{
private const string SE_DEBUG_NAME = "SeDebugPrivilege";
/// <summary>
/// Gets all top-level windows on the screen.
/// </summary>
public static IEnumerable<IntPtr> TopLevelWindows => WindowHelper.EnumTopLevelWindows();
/// <summary>
/// Gets all the windows on the screen.
/// </summary>
public static IEnumerable<IntPtr> Windows => WindowHelper.EnumAllWindows();
/// <summary>
/// Gets the first process found matching the supplied process name
/// </summary>
/// <param name="processName"></param>
/// <returns></returns>
public static IntPtr GetMainWindowHandle(string processName)
{
var firstOrDefault = _Process.GetProcessesByName(processName);
var process = firstOrDefault.FirstOrDefault();
// TODO: Didnt C# 6 or 7 introduce nullable types? check back for it
if (process == null)
{
throw new ArgumentNullException(nameof(process));
}
return process.MainWindowHandle;
}
/// <summary>
/// Returns a new <see cref="System.Diagnostics.Process" /> component, given the identifier of a process.
/// </summary>
/// <param name="processId">The system-unique identifier of a process resource.</param>
/// <returns>
/// A <see cref="System.Diagnostics.Process" /> component that is associated with the local process resource
/// identified by the processId parameter.
/// </returns>
public static _Process FromProcessId(int processId)
{
return _Process.GetProcessById(processId);
}
/// <summary>
/// Creates a collection of new <see cref="Process" /> components and associates them with all the process resources
/// that share the specified class name.
/// </summary>
/// <param name="className">The class name string.</param>
/// <returns>
/// A collection of type <see cref="Process" /> that represents the process resources running the specified
/// application or file.
/// </returns>
public static IEnumerable<_Process> FromWindowClassName(string className)
{
return Windows.Where(window => WindowHelper.GetClassName(window) == className).Select(FromWindowHandle);
}
/// <summary>
/// Retrieves a new <see cref="Process" /> component that created the window.
/// </summary>
/// <param name="windowHandle">A handle to the window.</param>
/// <returns>
/// A <see cref="Process" />A <see cref="Process" /> component that is associated with the specified window
/// handle.
/// </returns>
public static _Process FromWindowHandle(IntPtr windowHandle)
{
//todo: come back to try and fix this cast
return FromProcessId((int)WindowHelper.GetWindowProcessId(windowHandle));
}
/// <summary>
/// Creates a collection of new <see cref="Process" /> components and associates them with all the process resources
/// that share the specified window title.
/// </summary>
/// <param name="windowTitle">The window title string.</param>
/// <returns>
/// A collection of type <see cref="Process" /> that represents the process resources running the specified
/// application or file.
/// </returns>
public static IEnumerable<_Process> FromWindowTitle(string windowTitle)
{
return Windows.Where(window => WindowHelper.GetWindowText(window) == windowTitle).Select(FromWindowHandle);
}
/// <summary>
/// Creates a collection of new <see cref="Process" /> components and associates them with all the process resources
/// that contain the specified window title.
/// </summary>
/// <param name="windowTitle">A part a window title string.</param>
/// <returns>
/// A collection of type <see cref="Process" /> that represents the process resources running the specified
/// application or file.
/// </returns>
public static IEnumerable<_Process> FromWindowTitleContains(string windowTitle)
{
return
Windows.Where(window => WindowHelper.GetWindowText(window).Contains(windowTitle))
.Select(FromWindowHandle);
}
public static IEnumerable<_Process> CollectFromInternalName(string name)
{
// TODO: clean up this block if the replacement below works
/*
var processes = new List<_Process>(_Process.GetProcesses());
return processes.Where(process =>
{
try
{
return Kernel32.Is32BitProcess(process.Handle) &&
process.MainModule.FileVersionInfo.InternalName != null &&
process.MainModule.FileVersionInfo.InternalName.ToLower() == name.ToLower();
}
catch (Win32Exception)
{
return false;
}
});
*/
return _Process.GetProcesses().ToArray().Where(process => !string.IsNullOrWhiteSpace(process.MainModule.FileVersionInfo.InternalName) &&
string.Equals(process.MainModule.FileVersionInfo.InternalName, name, StringComparison.CurrentCultureIgnoreCase));
}
public static IEnumerable<_Process> FindProcessesByProductName(string name)
{
var processes = new List<_Process>(_Process.GetProcesses());
// TODO: clean up this code block if replacement below works out
/*
return processes.Where(process => Kernel32.Is32BitProcess(process.Handle) &&
process.MainModule.FileVersionInfo.ProductName != null &&
string.Equals(process.MainModule.FileVersionInfo.ProductName, name,
StringComparison.CurrentCultureIgnoreCase));
*/
return processes.Where(process => !string.IsNullOrWhiteSpace(process.MainModule.FileVersionInfo.ProductName) &&
string.Equals(process.MainModule.FileVersionInfo.ProductName, name, StringComparison.CurrentCultureIgnoreCase));
}
public static _Process FromName(string name)
{
var firstOrDefault = _Process.GetProcessesByName(name);
var process = firstOrDefault.FirstOrDefault();
if (process == null)
{
throw new ArgumentNullException(nameof(process));
}
return process;
}
// TODO: come back and clean up these comment blocks if things dont explode
/*
public static List<_Process> FindProcessesByName(string name)
{
var processes = new List<_Process>(_Process.GetProcessesByName(name));
return processes.Where(process => Kernel32.Is32BitProcess(process.Handle)).ToList();
}
*/
/*
public static _Process FindProcessByName(string name)
{
var processes = FindProcessesByName(name);
return processes.Count == 0 ? null : processes[0];
}
*/
public static _Process ByInternalName(string name)
{
return CollectFromInternalName(name).FirstOrDefault();
//var processes = CollectFromInternalName(name).ToList();
//return processes.Count == 0 ? null : processes[0];
}
public static _Process GetByProductName(string name)
{
using (var firstOrDefault = FindProcessesByProductName(name).FirstOrDefault())
{
if (firstOrDefault == null)
{
throw new NullReferenceException($"Process {name} not found.");
}
return firstOrDefault;
}
//var processes = FindProcessesByProductName(name).ToList();
//return processes.Count == 0 ? null : processes[0];
}
public static string GetVersionInfo(_Process process)
{
return
$"{process.MainModule.FileVersionInfo.FileDescription} {process.MainModule.FileVersionInfo.FileMajorPart}.{process.MainModule.FileVersionInfo.FileMinorPart}.{process.MainModule.FileVersionInfo.FileBuildPart} {process.MainModule.FileVersionInfo.FilePrivatePart}";
}
public static _Process SelectFromName(string internalName)
{
for (;;)
{
var processList = CollectFromInternalName(internalName).ToList();
if (processList.Count == 0)
throw new Exception($"No '{internalName}' processes found");
try
{
if (processList.Count == 1)
return processList[0];
Console.WriteLine("Select process:");
for (var i = 0; i < processList.Count; ++i)
{
var debugging = false;
Kernel32.CheckRemoteDebuggerPresent(processList[i].Handle, ref debugging);
Console.WriteLine(
$"[{i}] {processList[i].GetVersionInfo()} PID: {processList[i].Id} {(debugging ? "(Already debugging)" : "")}");
/*
Console.WriteLine("[{0}] {1} PID: {2} {3}",
i,
GetVersionInfo(processList[i]),
processList[i].Id,
debugging ? "(Already debugging)" : "");
*/
}
Console.WriteLine();
Console.Write("> ");
var index = Convert.ToInt32(Console.ReadLine());
return processList[index];
}
catch (Exception ex)
{
if (processList.Count == 1)
throw new Exception(ex.Message);
}
}
}
public static string GetProcessUser(_Process process)
{
IntPtr processHandle = IntPtr.Zero;
try
{
//todo: Access level should be query right?
Advapi32.OpenProcessToken(process.Handle, TokenAccessLevels.Query, out processHandle);
System.Security.Principal.WindowsIdentity wi = new System.Security.Principal.WindowsIdentity(processHandle);
string user = wi.Name;
return user.Contains(@"\") ? user.Substring(user.IndexOf(@"\") + 1) : user;
}
catch
{
return null;
}
finally
{
if (processHandle != IntPtr.Zero)
{
Kernel32.CloseHandle(processHandle);
}
}
}
public static string GetProcessUser(int processID) => GetProcessUser(_Process.GetProcessById(processID));
public static bool SetDebugPrivileges()
{
// TODO: is this playing nice after we revised the struct?
IntPtr hToken;
LUID luidSeDebugNameValue;
TOKEN_PRIVILEGES tkpPrivileges;
if (
!Advapi32.OpenProcessToken(Kernel32.GetCurrentProcess(),
TokenAccessLevels.AdjustPrivileges | TokenAccessLevels.Query, out hToken))
return false;
if (!Advapi32.LookupPrivilegeValue(null, SE_DEBUG_NAME, out luidSeDebugNameValue))
{
Kernel32.CloseHandle(hToken);
return false;
}
tkpPrivileges.PrivilegeCount = 1;
tkpPrivileges.Attributes.Luid = luidSeDebugNameValue;
tkpPrivileges.Attributes.Attributes = PrivilegeAttributes.SE_PRIVILEGE_ENABLED;
if (Advapi32.AdjustTokenPrivileges(hToken, false, ref tkpPrivileges, 0, IntPtr.Zero, IntPtr.Zero))
return Kernel32.CloseHandle(hToken);
Kernel32.CloseHandle(hToken);
return false;
}
}
}