Repository navigation
Expand file tree
/
Copy pathWndProcHook.cs
More file actions
119 lines (92 loc) · 3.02 KB
/
Copy pathWndProcHook.cs
File metadata and controls
119 lines (92 loc) · 3.02 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
using System;
using System.ComponentModel;
using System.Linq;
using System.Runtime.InteropServices;
using Process.NET.Applied;
using Process.NET.Native;
using Process.NET.Native.Types;
namespace Process.NET.Windows
{
public delegate IntPtr WindowProc(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
public abstract class WindowProcHook : IApplied
{
// ReSharper disable once InconsistentNaming
private const int GWL_WNDPROC = -4;
private WindowProc _newCallback;
private IntPtr _oldCallback;
protected WindowProcHook(IntPtr handle, string identifier = "")
{
if (string.IsNullOrEmpty(identifier))
{
identifier = "WindowProcHook - " + handle.ToString("X");
}
Identifier = identifier;
Handle = handle;
}
protected WindowProcHook(string procName, int index = 0)
{
var processesByName = System.Diagnostics.Process.GetProcessesByName(procName).ToList();
if (processesByName == null)
{
throw new NullReferenceException($"Could not find a process by the name of {procName}");
}
var process = index == 0 ? processesByName.First() : processesByName[index];
Identifier = $"WndProc hook - {process.MainWindowTitle}";
Handle = process.MainWindowHandle;
}
protected IntPtr Handle { get; set; }
public void Enable()
{
_newCallback = OnWndProc;
_oldCallback = Kernel32.SetWindowLongPtr(Handle, GWL_WNDPROC,
Marshal.GetFunctionPointerForDelegate(_newCallback));
if (_oldCallback == IntPtr.Zero)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
IsEnabled = true;
}
public string Identifier { get; }
public bool IsDisposed { get; protected set; }
public bool IsEnabled { get; protected set; }
public bool MustBeDisposed { get; set; } = true;
public void Disable()
{
if (_newCallback == null)
{
return;
}
Kernel32.SetWindowLongPtr(Handle, GWL_WNDPROC, _oldCallback);
_newCallback = null;
IsEnabled = false;
}
public void Dispose()
{
if (IsDisposed)
{
return;
}
IsDisposed = true;
if (IsEnabled)
{
Disable();
}
GC.SuppressFinalize(this);
}
protected virtual IntPtr OnWndProc(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam)
{
return Kernel32.CallWindowProc(_oldCallback, hWnd, msg, wParam, lParam);
}
~WindowProcHook()
{
if (MustBeDisposed)
{
Dispose();
}
}
public override string ToString()
{
return Identifier;
}
}
}