-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProcessCapture.cs
113 lines (99 loc) · 3.13 KB
/
ProcessCapture.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
using System;
using System.Diagnostics;
namespace LiveSplit.TOEM
{
public class ProcessCapture
{
/// <summary>
/// The name of the process to hook into if running.
/// </summary>
public string ProcessName { get; }
/// <summary>
/// A reference to the currently hooked process, if any, or null.
/// </summary>
public Process HookedProcess { get { return _process; } }
/// <summary>
/// Whether or not the memory interface is currently hooked. Will not trigger a hook attempt.
/// </summary>
public bool IsHooked { get { return CheckHook(); } }
/// <summary>
/// Number of seconds in between hooking attempts
/// </summary>
public int HookAttemptDelay { get; set; } = 3;
/// <summary>
/// Event raised whenever a new process has been hooked.
/// </summary>
public event EventHandler ProcessHooked;
/// <summary>
/// Event raised whenever a previously hooked process has been detected as lost (exited).
/// </summary>
public event EventHandler ProcessLost;
private Process _process = null;
private bool _isHooked = false;
private DateTime _lastHookAttempt;
public ProcessCapture(string processName)
{
ProcessName = processName;
}
public bool CheckHook()
{
// Check if process has exited since last check
if (_process != null)
{
if (_process.HasExited)
{
Unhook();
}
else
{
_isHooked = true;
}
}
return _isHooked;
}
public bool EnsureProcessHook()
{
CheckHook();
// If not currently hook, check if hook attempt should be made
if (!_isHooked && _lastHookAttempt.AddSeconds(HookAttemptDelay) <= DateTime.Now)
{
_lastHookAttempt = DateTime.Now;
Process[] processes = Process.GetProcessesByName(ProcessName);
if (processes != null && processes.Length > 0)
{
_process = processes[0];
_isHooked = true;
OnProcessHooked(new EventArgs());
}
else
{
_process = null;
_isHooked = false;
}
}
return _isHooked;
}
public void Unhook()
{
OnProcessLost(new EventArgs());
_isHooked = false;
_process = null;
}
public void Dispose()
{
if (_process != null)
{
_process.Dispose();
_process = null;
}
}
protected virtual void OnProcessHooked(EventArgs e)
{
ProcessHooked?.Invoke(this, e);
}
protected virtual void OnProcessLost(EventArgs e)
{
ProcessLost?.Invoke(this, e);
}
}
}