-
Notifications
You must be signed in to change notification settings - Fork 0
/
InputMessageLoop.cs
126 lines (103 loc) · 3.4 KB
/
InputMessageLoop.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
using System.Diagnostics;
using System.Runtime.InteropServices;
using Vanara.PInvoke;
using static Vanara.PInvoke.User32;
namespace PreciseThreeFingersDrag
{
public class InputMessageLoop : IDisposable
{
internal string WindowId { get; private set; }
public Thread? HwndThread { get; private set; }
public bool IsCreated => Handle != 0;
public nint Handle { get; private set; }
public InputMessageLoop(InputMessageEvent handler)
{
WindowId = "PTFD_" + Guid.NewGuid();
InputMessageReceived += handler;
}
protected unsafe nint WndProc(HWND hwnd, uint msg, IntPtr wParam, IntPtr lParam)
{
return DefWindowProc(hwnd, msg, wParam, lParam);
}
public delegate void InputMessageEvent(IntPtr lParam);
public event InputMessageEvent InputMessageReceived;
public nint Create()
{
ManualResetEvent mutHwnd = new(false);
HwndThread = new Thread(() =>
{
WNDCLASS wndClass = new()
{
lpfnWndProc = new WindowProc(WndProc),
lpszClassName = WindowId,
};
ushort result = RegisterClass(wndClass);
if (result == 0)
{
throw new Exception(Marshal.GetLastPInvokeErrorMessage());
}
nint hwnd = CreateWindow(lpClassName: WindowId).DangerousGetHandle();
if (hwnd == 0)
{
throw new Exception(Marshal.GetLastPInvokeErrorMessage());
}
Handle = hwnd;
_ = mutHwnd.Set();
RunMessageLoop();
_ = DestroyWindow(hwnd);
});
HwndThread.Start();
_ = mutHwnd.WaitOne();
mutHwnd.Dispose();
return Handle;
}
private void RunMessageLoop()
{
Debug.WriteLine("InputHwnd: message loop started");
bool quit = false;
while (!quit)
{
_ = new MSG();
int result = GetMessage(out MSG msg, IntPtr.Zero, 0, 0);
if (result is 0 or (-1))
{
break;
}
if (msg.message == (uint)WindowMessage.WM_QUIT)
{
Debug.WriteLine("InputHwnd: got WM_QUIT");
quit = true;
}
if (msg.message == (uint)WindowMessage.WM_INPUT)
{
InputMessageReceived.Invoke(msg.lParam);
}
_ = TranslateMessage(msg);
_ = DispatchMessage(msg);
}
Debug.WriteLine("InputHwnd: message loop exited");
}
public void StopMessageLoop()
{
if (Handle != 0)
{
Debug.WriteLine("sent quit");
_ = PostMessage((HWND)Handle, (uint)WindowMessage.WM_QUIT, 0, 0);
Handle = nint.Zero;
}
}
public bool IsDisposed { get; private set; }
public void Dispose()
{
if (!IsDisposed)
{
StopMessageLoop();
IsDisposed = true;
}
}
~InputMessageLoop()
{
Dispose();
}
}
}