-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBrowserProcessService.cs
More file actions
72 lines (65 loc) · 2.59 KB
/
Copy pathBrowserProcessService.cs
File metadata and controls
72 lines (65 loc) · 2.59 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
// Safely closes affected browsers before their live profile data is edited.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
namespace NotiWhacker
{
internal sealed class BrowserStopResult
{
public HashSet<string> SafeToEdit { get; } = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
public List<string> Warnings { get; } = new List<string>();
}
internal static class BrowserProcessService
{
public static BrowserStopResult StopAffected(IEnumerable<string> processNames)
{
BrowserStopResult result = new BrowserStopResult();
foreach (string processName in processNames.Distinct(StringComparer.OrdinalIgnoreCase))
{
Process[] processes = Process.GetProcessesByName(processName);
// Ask top-level windows to close first so the browser can flush unrelated profile state.
foreach (Process process in processes)
{
try { process.CloseMainWindow(); } catch { }
}
foreach (Process process in processes)
{
try
{
if (!process.WaitForExit(5000))
{
process.Kill();
process.WaitForExit(5000);
}
}
catch (Exception ex) when (ex is Win32Exception || ex is InvalidOperationException || ex is NotSupportedException)
{
result.Warnings.Add("Could not stop " + processName + " process " + SafeProcessId(process) + ": " + ex.Message);
}
finally
{
process.Dispose();
}
}
Process[] remaining = Process.GetProcessesByName(processName);
bool stopped = remaining.Length == 0;
foreach (Process process in remaining) process.Dispose();
if (stopped)
{
result.SafeToEdit.Add(processName);
}
else
{
result.Warnings.Add(processName + " is still running; its selected permissions were not changed.");
}
}
return result;
}
private static string SafeProcessId(Process process)
{
try { return process.Id.ToString(); } catch { return "unknown"; }
}
}
}