Repository navigation
Expand file tree
/
Copy pathProgram.cs
More file actions
433 lines (365 loc) · 12.3 KB
/
Copy pathProgram.cs
File metadata and controls
433 lines (365 loc) · 12.3 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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
using System.Runtime.InteropServices;
using Microsoft.Win32;
namespace SideLock;
internal static class Program
{
[STAThread]
private static void Main()
{
using var singleInstanceMutex = new Mutex(initiallyOwned: true, @"Local\SideLock.SingleInstance", out var isFirstInstance);
if (!isFirstInstance)
{
return;
}
ApplicationConfiguration.Initialize();
Application.Run(new TrayApplicationContext());
}
}
internal sealed class TrayApplicationContext : ApplicationContext
{
private const string RunValueName = "SideLock";
private const string LegacyRunValueName = "Fix Side Keys Microphone";
private const string RunRegistryPath = @"Software\Microsoft\Windows\CurrentVersion\Run";
private readonly AppSettings _settings;
private readonly MouseHook _mouseHook;
private readonly NotifyIcon _notifyIcon;
private readonly ToolStripMenuItem _blockMouse5MenuItem;
private readonly ToolStripMenuItem _blockMouse4MenuItem;
private readonly ToolStripMenuItem _startWithWindowsMenuItem;
private bool _exiting;
public TrayApplicationContext()
{
MigrateLegacyStartupEntry();
_settings = AppSettings.Load();
_mouseHook = new MouseHook(_settings.BlockMouse4, _settings.BlockMouse5);
_startWithWindowsMenuItem = new ToolStripMenuItem("Start with Windows")
{
CheckOnClick = true,
Checked = IsStartWithWindowsEnabled()
};
_startWithWindowsMenuItem.CheckedChanged += StartWithWindowsMenuItem_CheckedChanged;
var settingsMenuItem = new ToolStripMenuItem("Settings");
settingsMenuItem.DropDownItems.Add(_startWithWindowsMenuItem);
_blockMouse5MenuItem = new ToolStripMenuItem("Block Mouse5")
{
CheckOnClick = true,
Checked = _settings.BlockMouse5
};
_blockMouse5MenuItem.CheckedChanged += BlockMouse5MenuItem_CheckedChanged;
_blockMouse4MenuItem = new ToolStripMenuItem("Block Mouse4")
{
CheckOnClick = true,
Checked = _settings.BlockMouse4
};
_blockMouse4MenuItem.CheckedChanged += BlockMouse4MenuItem_CheckedChanged;
var exitMenuItem = new ToolStripMenuItem("Exit");
exitMenuItem.Click += (_, _) => ExitApplication();
var menu = new ContextMenuStrip();
menu.Items.Add(settingsMenuItem);
menu.Items.Add(new ToolStripSeparator());
menu.Items.Add(_blockMouse5MenuItem);
menu.Items.Add(_blockMouse4MenuItem);
menu.Items.Add(new ToolStripSeparator());
menu.Items.Add(exitMenuItem);
_notifyIcon = new NotifyIcon
{
Icon = AppIcon.Load(),
Text = "SideLock",
ContextMenuStrip = menu,
Visible = true
};
_mouseHook.Install();
}
private void BlockMouse5MenuItem_CheckedChanged(object? sender, EventArgs e)
{
_settings.BlockMouse5 = _blockMouse5MenuItem.Checked;
_mouseHook.BlockMouse5 = _settings.BlockMouse5;
_settings.Save();
}
private void BlockMouse4MenuItem_CheckedChanged(object? sender, EventArgs e)
{
_settings.BlockMouse4 = _blockMouse4MenuItem.Checked;
_mouseHook.BlockMouse4 = _settings.BlockMouse4;
_settings.Save();
}
private void StartWithWindowsMenuItem_CheckedChanged(object? sender, EventArgs e)
{
SetStartWithWindows(_startWithWindowsMenuItem.Checked);
}
private static bool IsStartWithWindowsEnabled()
{
using var key = Registry.CurrentUser.OpenSubKey(RunRegistryPath, writable: false);
return key?.GetValue(RunValueName) is string;
}
private static void MigrateLegacyStartupEntry()
{
using var key = Registry.CurrentUser.OpenSubKey(RunRegistryPath, writable: true);
if (key?.GetValue(LegacyRunValueName) is not string)
{
return;
}
var executablePath = Environment.ProcessPath;
if (!string.IsNullOrEmpty(executablePath))
{
key.SetValue(RunValueName, $"\"{executablePath}\"");
}
key.DeleteValue(LegacyRunValueName, throwOnMissingValue: false);
}
private static void SetStartWithWindows(bool enabled)
{
using var key = Registry.CurrentUser.OpenSubKey(RunRegistryPath, writable: true)
?? Registry.CurrentUser.CreateSubKey(RunRegistryPath, writable: true);
if (enabled)
{
var executablePath = Environment.ProcessPath
?? throw new InvalidOperationException("Cannot determine the application path.");
key.SetValue(RunValueName, $"\"{executablePath}\"");
}
else
{
key.DeleteValue(RunValueName, throwOnMissingValue: false);
}
}
private void ExitApplication()
{
if (_exiting)
{
return;
}
_exiting = true;
_mouseHook.Dispose();
_notifyIcon.Visible = false;
_notifyIcon.Dispose();
ExitThread();
}
protected override void ExitThreadCore()
{
if (!_exiting)
{
ExitApplication();
return;
}
base.ExitThreadCore();
}
}
internal sealed class MouseHook : IDisposable
{
private const int WhMouseLl = 14;
private const int WmXButtonDown = 0x020B;
private const int WmXButtonUp = 0x020C;
private const ushort XButton1 = 1; // Mouse4 / Back
private const ushort XButton2 = 2; // Mouse5 / Forward
private const ushort VkF23 = 0x86;
private const ushort VkF24 = 0x87;
private const uint KeyeventfKeyup = 0x0002;
private readonly LowLevelMouseProc _callback;
private IntPtr _hookId;
private bool _mouse4Pressed;
private bool _mouse5Pressed;
public MouseHook(bool blockMouse4, bool blockMouse5)
{
BlockMouse4 = blockMouse4;
BlockMouse5 = blockMouse5;
_callback = HookCallback;
}
public bool BlockMouse4 { get; set; }
public bool BlockMouse5 { get; set; }
public void Install()
{
if (_hookId != IntPtr.Zero)
{
return;
}
using var process = System.Diagnostics.Process.GetCurrentProcess();
using var module = process.MainModule;
_hookId = SetWindowsHookEx(WhMouseLl, _callback, GetModuleHandle(module?.ModuleName), 0);
if (_hookId == IntPtr.Zero)
{
throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error(), "Unable to install the mouse hook.");
}
}
private IntPtr HookCallback(int code, IntPtr wParam, IntPtr lParam)
{
if (code < 0)
{
return CallNextHookEx(_hookId, code, wParam, lParam);
}
var message = unchecked((int)wParam.ToInt64());
if (message is not (WmXButtonDown or WmXButtonUp))
{
return CallNextHookEx(_hookId, code, wParam, lParam);
}
var data = Marshal.PtrToStructure<MsllHookStruct>(lParam);
var xButton = unchecked((ushort)(data.MouseData >> 16));
var handled = xButton switch
{
XButton1 => HandleMouseButton(message, BlockMouse4, ref _mouse4Pressed, VkF23),
XButton2 => HandleMouseButton(message, BlockMouse5, ref _mouse5Pressed, VkF24),
_ => false
};
return handled ? (IntPtr)1 : CallNextHookEx(_hookId, code, wParam, lParam);
}
private static bool HandleMouseButton(int message, bool isBlocked, ref bool isPressed, ushort virtualKey)
{
if (message == WmXButtonDown && isBlocked)
{
if (!isPressed)
{
SendKey(virtualKey, keyUp: false);
isPressed = true;
}
return true;
}
if (message == WmXButtonUp && isPressed)
{
SendKey(virtualKey, keyUp: true);
isPressed = false;
return true;
}
return false;
}
private static void SendKey(ushort virtualKey, bool keyUp)
{
var input = new Input
{
Type = 1,
Union = new InputUnion
{
Keyboard = new KeybdInput
{
VirtualKey = virtualKey,
Flags = keyUp ? KeyeventfKeyup : 0
}
}
};
SendInput(1, [input], Marshal.SizeOf<Input>());
}
public void Dispose()
{
if (_mouse4Pressed)
{
SendKey(VkF23, keyUp: true);
_mouse4Pressed = false;
}
if (_mouse5Pressed)
{
SendKey(VkF24, keyUp: true);
_mouse5Pressed = false;
}
if (_hookId != IntPtr.Zero)
{
UnhookWindowsHookEx(_hookId);
_hookId = IntPtr.Zero;
}
}
private delegate IntPtr LowLevelMouseProc(int code, IntPtr wParam, IntPtr lParam);
[StructLayout(LayoutKind.Sequential)]
private struct MsllHookStruct
{
public Point Point;
public uint MouseData;
public uint Flags;
public uint Time;
public IntPtr ExtraInfo;
}
[StructLayout(LayoutKind.Sequential)]
private struct Point
{
public int X;
public int Y;
}
[StructLayout(LayoutKind.Sequential)]
private struct Input
{
public uint Type;
public InputUnion Union;
}
[StructLayout(LayoutKind.Explicit)]
private struct InputUnion
{
[FieldOffset(0)]
public KeybdInput Keyboard;
}
[StructLayout(LayoutKind.Sequential)]
private struct KeybdInput
{
public ushort VirtualKey;
public ushort ScanCode;
public uint Flags;
public uint Time;
public IntPtr ExtraInfo;
}
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelMouseProc callback, IntPtr module, uint threadId);
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool UnhookWindowsHookEx(IntPtr hook);
[DllImport("user32.dll")]
private static extern IntPtr CallNextHookEx(IntPtr hook, int code, IntPtr wParam, IntPtr lParam);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr GetModuleHandle(string? moduleName);
[DllImport("user32.dll", SetLastError = true)]
private static extern uint SendInput(uint inputCount, Input[] inputs, int inputSize);
}
internal sealed class AppSettings
{
private static readonly string FilePath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"SideLock",
"settings.json");
public bool BlockMouse4 { get; set; }
public bool BlockMouse5 { get; set; }
public static AppSettings Load()
{
try
{
if (File.Exists(FilePath))
{
return System.Text.Json.JsonSerializer.Deserialize<AppSettings>(File.ReadAllText(FilePath)) ?? new AppSettings();
}
var legacyPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"FixSideKeysMicrophone",
"settings.json");
if (File.Exists(legacyPath))
{
return System.Text.Json.JsonSerializer.Deserialize<AppSettings>(File.ReadAllText(legacyPath)) ?? new AppSettings();
}
}
catch (IOException)
{
}
catch (System.Text.Json.JsonException)
{
}
return new AppSettings();
}
public void Save()
{
var directory = Path.GetDirectoryName(FilePath)!;
Directory.CreateDirectory(directory);
File.WriteAllText(FilePath, System.Text.Json.JsonSerializer.Serialize(this));
}
}
internal static class AppIcon
{
public static Icon Load()
{
try
{
if (Environment.ProcessPath is { Length: > 0 } executablePath)
{
var icon = Icon.ExtractAssociatedIcon(executablePath);
if (icon is not null)
{
return icon;
}
}
}
catch
{
// Use the embedded icon when extracting the executable icon is unavailable.
}
return new Icon(typeof(AppIcon), "sidelock.ico");
}
}