Repository navigation
Expand file tree
/
Copy pathMagicVolume.cs
More file actions
692 lines (620 loc) · 31.5 KB
/
Copy pathMagicVolume.cs
File metadata and controls
692 lines (620 loc) · 31.5 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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
// MagicVolume - makes the Apple Magic Keyboard's top row behave like it does on
// a Mac, on Windows, without a paid driver.
//
// Measured on this machine (see README.md): the Magic Keyboard delivers its top
// row to Windows as plain F1..F12. It emits no HID Consumer Control usages, so
// nothing maps them to brightness/media/volume. The fn key IS transmitted, as
// Apple vendor usage 0xFF00:0x03 inside keyboard report 1, but Windows' in-box
// keyboard driver only translates usage page 0x07 and discards that bit before
// any userspace program can see it - and the raw report is unreadable
// (ACCESS_DENIED, anti-keylogger protection). So fn cannot be the modifier;
// hold the configured PassThroughModifier (default SHIFT) for real F-keys.
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
// ---------------------------------------------------------------- CoreAudio
[ComImport, Guid("BCDE0395-E52F-467C-8E3D-C4579291692E")] class MMDeviceEnumerator { }
[ComImport, Guid("A95664D2-9614-4F35-A746-DE8DB63617E6"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IMMDeviceEnumerator {
int EnumAudioEndpoints(int flow, int mask, out IntPtr col);
int GetDefaultAudioEndpoint(int flow, int role, out IMMDevice dev);
}
[ComImport, Guid("D666063F-1587-4E43-81F1-B948E807363F"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IMMDevice {
int Activate(ref Guid iid, int ctx, IntPtr p, [MarshalAs(UnmanagedType.IUnknown)] out object o);
}
[ComImport, Guid("5CDF2C82-841E-4546-9722-0CF74078229A"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IAudioEndpointVolume {
int RegisterControlChangeNotify(IntPtr n);
int UnregisterControlChangeNotify(IntPtr n);
int GetChannelCount(out uint c);
int SetMasterVolumeLevel(float d, ref Guid ctx);
int SetMasterVolumeLevelScalar(float d, ref Guid ctx);
int GetMasterVolumeLevel(out float d);
int GetMasterVolumeLevelScalar(out float d);
int SetChannelVolumeLevel(uint ch, float d, ref Guid ctx);
int SetChannelVolumeLevelScalar(uint ch, float d, ref Guid ctx);
int GetChannelVolumeLevel(uint ch, out float d);
int GetChannelVolumeLevelScalar(uint ch, out float d);
int SetMute([MarshalAs(UnmanagedType.Bool)] bool m, ref Guid ctx);
int GetMute([MarshalAs(UnmanagedType.Bool)] out bool m);
}
class MagicVolume {
// ------------------------------------------------------------ interop
const int WH_KEYBOARD_LL = 13;
const int WM_KEYDOWN = 0x0100, WM_SYSKEYDOWN = 0x0104;
const int WM_KEYUP = 0x0101, WM_SYSKEYUP = 0x0105;
const uint LLKHF_INJECTED = 0x10, LLKHF_LOWER_IL_INJECTED = 0x02;
const int VK_SHIFT = 0x10, VK_CONTROL = 0x11, VK_MENU = 0x12, VK_LWIN = 0x5B, VK_RWIN = 0x5C;
const byte VK_VOLUME_MUTE = 0xAD, VK_VOLUME_DOWN = 0xAE, VK_VOLUME_UP = 0xAF;
const byte VK_MEDIA_NEXT = 0xB0, VK_MEDIA_PREV = 0xB1, VK_MEDIA_STOP = 0xB2, VK_MEDIA_PLAY = 0xB3;
const byte VK_BROWSER_BACK = 0xA6, VK_BROWSER_FORWARD = 0xA7;
const uint KEYEVENTF_KEYUP = 0x0002;
delegate IntPtr HookProc(int code, IntPtr wParam, IntPtr lParam);
delegate bool MonitorEnumProc(IntPtr hMon, IntPtr hdc, IntPtr rect, IntPtr data);
[StructLayout(LayoutKind.Sequential)]
struct KBDLLHOOKSTRUCT { public uint vkCode, scanCode, flags, time; public IntPtr dwExtraInfo; }
[StructLayout(LayoutKind.Sequential)]
struct MSG { public IntPtr hwnd; public uint message; public IntPtr wParam, lParam; public uint time; public int x, y; }
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
struct PHYSICAL_MONITOR {
public IntPtr hPhysicalMonitor;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] public string szDescription;
}
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr SetWindowsHookEx(int id, HookProc fn, IntPtr mod, uint tid);
[DllImport("user32.dll")] static extern bool UnhookWindowsHookEx(IntPtr hk);
[DllImport("user32.dll")] static extern IntPtr CallNextHookEx(IntPtr hk, int c, IntPtr w, IntPtr l);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)] static extern IntPtr GetModuleHandle(string n);
[DllImport("user32.dll")] static extern short GetAsyncKeyState(int vk);
[DllImport("user32.dll")] static extern void keybd_event(byte vk, byte scan, uint flags, UIntPtr extra);
[DllImport("user32.dll")] static extern int GetMessageW(out MSG m, IntPtr h, uint a, uint b);
[DllImport("user32.dll")] static extern UIntPtr SetTimer(IntPtr hwnd, UIntPtr id, uint ms, IntPtr fn);
const uint WM_TIMER = 0x0113;
[DllImport("user32.dll")] static extern bool LockWorkStation();
[DllImport("user32.dll")] static extern bool EnumDisplayMonitors(IntPtr hdc, IntPtr clip, MonitorEnumProc fn, IntPtr data);
[DllImport("kernel32.dll")] static extern bool Beep(uint freq, uint dur);
[DllImport("powrprof.dll", SetLastError = true)]
static extern bool SetSuspendState(bool hibernate, bool forceCritical, bool disableWakeEvent);
// --- dimmer overlay ---
const int WS_EX_LAYERED = 0x00080000, WS_EX_TRANSPARENT = 0x00000020, WS_EX_TOPMOST = 0x00000008;
const int WS_EX_TOOLWINDOW = 0x00000080, WS_EX_NOACTIVATE = 0x08000000;
const uint WS_POPUP = 0x80000000;
const int SW_HIDE = 0, SW_SHOWNOACTIVATE = 4;
const uint LWA_ALPHA = 0x2;
const int SM_XVIRTUALSCREEN = 76, SM_YVIRTUALSCREEN = 77, SM_CXVIRTUALSCREEN = 78, SM_CYVIRTUALSCREEN = 79;
const uint SWP_NOACTIVATE = 0x0010;
const uint WM_APP_SETLEVEL = 0x8001, WM_DISPLAYCHANGE = 0x007E;
static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
delegate IntPtr WndProcDel(IntPtr h, uint m, IntPtr w, IntPtr l);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
struct WNDCLASS {
public uint style; public IntPtr lpfnWndProc; public int cbClsExtra, cbWndExtra;
public IntPtr hInstance, hIcon, hCursor, hbrBackground;
public string lpszMenuName, lpszClassName;
}
[DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern ushort RegisterClassW(ref WNDCLASS c);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
static extern IntPtr CreateWindowExW(int ex, string cls, string title, uint style,
int x, int y, int w, int h, IntPtr parent, IntPtr menu, IntPtr inst, IntPtr p);
[DllImport("user32.dll")] static extern IntPtr DefWindowProcW(IntPtr h, uint m, IntPtr w, IntPtr l);
[DllImport("user32.dll")] static extern bool ShowWindow(IntPtr h, int cmd);
[DllImport("user32.dll")] static extern bool SetWindowPos(IntPtr h, IntPtr after, int x, int y, int w, int ht, uint flags);
[DllImport("user32.dll")] static extern bool SetLayeredWindowAttributes(IntPtr h, uint key, byte alpha, uint flags);
[DllImport("user32.dll")] static extern int GetSystemMetrics(int i);
[DllImport("user32.dll")] static extern bool PostMessageW(IntPtr h, uint msg, IntPtr w, IntPtr l);
[DllImport("user32.dll")] static extern bool TranslateMessage(ref MSG m);
[DllImport("user32.dll")] static extern IntPtr DispatchMessageW(ref MSG m);
[DllImport("gdi32.dll")] static extern IntPtr CreateSolidBrush(uint color);
[DllImport("dxva2.dll", SetLastError = true)]
static extern bool GetNumberOfPhysicalMonitorsFromHMONITOR(IntPtr hMon, out uint n);
[DllImport("dxva2.dll", SetLastError = true)]
static extern bool GetPhysicalMonitorsFromHMONITOR(IntPtr hMon, uint n, [Out] PHYSICAL_MONITOR[] p);
[DllImport("dxva2.dll", SetLastError = true)]
static extern bool GetMonitorBrightness(IntPtr h, out uint min, out uint cur, out uint max);
[DllImport("dxva2.dll", SetLastError = true)]
static extern bool SetMonitorBrightness(IntPtr h, uint val);
[DllImport("dxva2.dll")] static extern bool DestroyPhysicalMonitors(uint n, [In] PHYSICAL_MONITOR[] p);
// ------------------------------------------------------------ state
static HookProc _proc;
static MonitorEnumProc _monProc;
static IntPtr _hook = IntPtr.Zero;
static string _logPath;
static Dictionary<uint, string> _map = new Dictionary<uint, string>();
static HashSet<uint> _held = new HashSet<uint>();
static int _passThroughVk = VK_SHIFT;
static string _passThroughName = "SHIFT";
static uint _toggleVk = 0;
static int[] _toggleMods = new int[0];
static string _toggleName = "";
static bool _enabled = true;
static int _brightnessStep = 10;
static readonly object _logLock = new object();
static void Log(string msg) {
try {
lock (_logLock)
File.AppendAllText(_logPath, DateTime.Now.ToString("HH:mm:ss") + " " + msg + Environment.NewLine);
} catch { }
}
// ------------------------------------------------------------ keys
static void Tap(byte vk) {
keybd_event(vk, 0, 0, UIntPtr.Zero);
keybd_event(vk, 0, KEYEVENTF_KEYUP, UIntPtr.Zero);
}
static int NameToVk(string s) {
s = s.Trim().ToUpperInvariant();
if (s.Length == 0) return -1;
if (s.Length == 1) {
char c = s[0];
if (c >= 'A' && c <= 'Z') return c;
if (c >= '0' && c <= '9') return c;
}
if (s[0] == 'F' && s.Length <= 3) {
int n;
if (int.TryParse(s.Substring(1), out n) && n >= 1 && n <= 24) return 0x70 + n - 1;
}
switch (s) {
case "TAB": return 0x09; case "ENTER": case "RETURN": return 0x0D;
case "SPACE": return 0x20; case "ESC": case "ESCAPE": return 0x1B;
case "BACKSPACE": return 0x08; case "DELETE": case "DEL": return 0x2E;
case "INSERT": case "INS": return 0x2D;
case "HOME": return 0x24; case "END": return 0x23;
case "PGUP": case "PAGEUP": return 0x21;
case "PGDN": case "PAGEDOWN": return 0x22;
case "LEFT": return 0x25; case "UP": return 0x26;
case "RIGHT": return 0x27; case "DOWN": return 0x28;
case "PRTSC": case "PRINTSCREEN": return 0x2C;
case "WIN": case "CMD": case "COMMAND": return VK_LWIN;
case "CTRL": case "CONTROL": return VK_CONTROL;
case "ALT": case "OPTION": return VK_MENU;
case "SHIFT": return VK_SHIFT;
default: return -1;
}
}
static bool IsModName(string s) {
switch (s.Trim().ToUpperInvariant()) {
case "WIN": case "CMD": case "COMMAND":
case "CTRL": case "CONTROL":
case "ALT": case "OPTION":
case "SHIFT": return true;
default: return false;
}
}
// Sends a combo such as WIN+TAB or CTRL+ALT+S.
static void SendCombo(string spec) {
var mods = new List<byte>();
byte key = 0;
foreach (string part in spec.Split('+')) {
string t = part.Trim();
if (t.Length == 0) continue;
int vk = NameToVk(t);
if (vk < 0) continue;
if (IsModName(t)) mods.Add((byte)vk); else key = (byte)vk;
}
if (key == 0 && mods.Count == 0) return;
// The user is physically holding the F-key we swallowed; any modifier
// they happen to be leaning on would corrupt the combo, so send clean.
foreach (byte m in mods) keybd_event(m, 0, 0, UIntPtr.Zero);
if (key != 0) {
keybd_event(key, 0, 0, UIntPtr.Zero);
keybd_event(key, 0, KEYEVENTF_KEYUP, UIntPtr.Zero);
}
for (int i = mods.Count - 1; i >= 0; i--)
keybd_event(mods[i], 0, KEYEVENTF_KEYUP, UIntPtr.Zero);
}
// ------------------------------------------------------------ microphone
static void MicToggle() {
try {
var en = (IMMDeviceEnumerator)new MMDeviceEnumerator();
IMMDevice dev;
if (en.GetDefaultAudioEndpoint(1 /*eCapture*/, 1 /*eMultimedia*/, out dev) != 0 || dev == null) {
Log("mic: no default capture device"); return;
}
Guid iid = typeof(IAudioEndpointVolume).GUID;
object o;
dev.Activate(ref iid, 23, IntPtr.Zero, out o);
var vol = (IAudioEndpointVolume)o;
bool muted;
vol.GetMute(out muted);
Guid ctx = Guid.Empty;
vol.SetMute(!muted, ref ctx);
Log("mic " + (!muted ? "MUTED" : "unmuted"));
if (!muted) { Beep(520, 60); } else { Beep(880, 60); }
} catch (Exception ex) { Log("mic toggle failed: " + ex.Message); }
}
// ------------------------------------------------------------ brightness
// Desktop monitors have no brightness VK; this drives DDC/CI over the video
// cable, which is what the monitor's own OSD buttons use.
static List<IntPtr> CollectMonitors() {
var handles = new List<IntPtr>();
var mons = new List<IntPtr>();
_monProc = delegate(IntPtr hMon, IntPtr hdc, IntPtr r, IntPtr d) { mons.Add(hMon); return true; };
EnumDisplayMonitors(IntPtr.Zero, IntPtr.Zero, _monProc, IntPtr.Zero);
foreach (IntPtr hMon in mons) {
uint n;
if (!GetNumberOfPhysicalMonitorsFromHMONITOR(hMon, out n) || n == 0) continue;
var arr = new PHYSICAL_MONITOR[n];
if (!GetPhysicalMonitorsFromHMONITOR(hMon, n, arr)) continue;
for (int i = 0; i < n; i++) handles.Add(arr[i].hPhysicalMonitor);
}
return handles;
}
// ------------------------------------------------------ dimmer overlay
// A monitor's own backlight is not reachable on most desktop setups, so
// "brightness" here is a black, click-through, always-on-top window laid
// over every screen. 100 = hidden, 50 = half-opacity black, 0 = fully black.
static IntPtr _overlayHwnd = IntPtr.Zero;
static WndProcDel _overlayProc;
static int _level = 100; // current brightness, 0..100
static int _minLevel = 0;
static readonly ManualResetEvent _overlayReady = new ManualResetEvent(false);
static IntPtr OverlayWndProc(IntPtr h, uint msg, IntPtr w, IntPtr l) {
if (msg == WM_APP_SETLEVEL) {
int lvl = w.ToInt32();
if (lvl >= 100) {
ShowWindow(h, SW_HIDE);
} else {
byte alpha = (byte)((100 - lvl) * 255 / 100);
SetLayeredWindowAttributes(h, 0, alpha, LWA_ALPHA);
SizeToVirtualScreen(h);
ShowWindow(h, SW_SHOWNOACTIVATE);
}
return IntPtr.Zero;
}
if (msg == WM_DISPLAYCHANGE) { SizeToVirtualScreen(h); return IntPtr.Zero; }
return DefWindowProcW(h, msg, w, l);
}
static void SizeToVirtualScreen(IntPtr h) {
SetWindowPos(h, HWND_TOPMOST,
GetSystemMetrics(SM_XVIRTUALSCREEN), GetSystemMetrics(SM_YVIRTUALSCREEN),
GetSystemMetrics(SM_CXVIRTUALSCREEN), GetSystemMetrics(SM_CYVIRTUALSCREEN),
SWP_NOACTIVATE);
}
static void OverlayThread() {
IntPtr inst = GetModuleHandle(null);
_overlayProc = OverlayWndProc;
var wc = new WNDCLASS();
wc.lpfnWndProc = Marshal.GetFunctionPointerForDelegate(_overlayProc);
wc.hInstance = inst;
wc.hbrBackground = CreateSolidBrush(0x000000);
wc.lpszClassName = "MagicVolumeDimmer";
RegisterClassW(ref wc);
_overlayHwnd = CreateWindowExW(
WS_EX_LAYERED | WS_EX_TRANSPARENT | WS_EX_TOPMOST | WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE,
"MagicVolumeDimmer", "", WS_POPUP,
GetSystemMetrics(SM_XVIRTUALSCREEN), GetSystemMetrics(SM_YVIRTUALSCREEN),
GetSystemMetrics(SM_CXVIRTUALSCREEN), GetSystemMetrics(SM_CYVIRTUALSCREEN),
IntPtr.Zero, IntPtr.Zero, inst, IntPtr.Zero);
if (_overlayHwnd == IntPtr.Zero) Log("dimmer: CreateWindowEx failed " + Marshal.GetLastWin32Error());
else Log("dimmer overlay ready");
_overlayReady.Set();
MSG m;
while (GetMessageW(out m, IntPtr.Zero, 0, 0) > 0) { TranslateMessage(ref m); DispatchMessageW(ref m); }
}
static void Dim(int delta) {
_overlayReady.WaitOne(2000);
if (_overlayHwnd == IntPtr.Zero) return;
int lvl = _level + delta;
if (lvl > 100) lvl = 100;
if (lvl < _minLevel) lvl = _minLevel;
if (lvl == _level) return;
_level = lvl;
PostMessageW(_overlayHwnd, WM_APP_SETLEVEL, new IntPtr(lvl), IntPtr.Zero);
}
static bool _brightnessWarned = false;
static void Brightness(int deltaPercent) {
var handles = CollectMonitors();
if (handles.Count == 0) {
if (!_brightnessWarned) { Log("brightness: no physical monitors found"); _brightnessWarned = true; }
return;
}
int changed = 0;
foreach (IntPtr h in handles) {
uint min, cur, max;
if (!GetMonitorBrightness(h, out min, out cur, out max)) continue;
long range = (long)max - min;
if (range <= 0) continue;
long step = range * deltaPercent / 100;
if (step == 0) step = deltaPercent > 0 ? 1 : -1;
long val = (long)cur + step;
if (val < min) val = min;
if (val > max) val = max;
if (SetMonitorBrightness(h, (uint)val)) changed++;
}
var arr2 = new PHYSICAL_MONITOR[handles.Count];
for (int i = 0; i < handles.Count; i++) arr2[i].hPhysicalMonitor = handles[i];
DestroyPhysicalMonitors((uint)arr2.Length, arr2);
if (changed == 0 && !_brightnessWarned) {
Log("brightness: no monitor accepted DDC/CI. Enable DDC/CI in the monitor's OSD menu, "
+ "or map F1/F2 to something else in mapping.ini.");
_brightnessWarned = true;
}
}
// ------------------------------------------------------------ actions
// Slow or blocking work must not run inside the hook, or every keystroke on
// the machine stalls behind it.
static void Async(ThreadStart fn) {
ThreadPool.QueueUserWorkItem(delegate(object s) {
try { fn(); } catch (Exception ex) { Log("action failed: " + ex.Message); }
});
}
static bool Fire(string action) {
if (action.StartsWith("KEYS:")) {
string combo = action.Substring(5);
Async(delegate { SendCombo(combo); });
return true;
}
switch (action) {
case "VOLUME_UP": Tap(VK_VOLUME_UP); return true;
case "VOLUME_DOWN": Tap(VK_VOLUME_DOWN); return true;
case "MUTE": Tap(VK_VOLUME_MUTE); return true;
case "MEDIA_PLAY": Tap(VK_MEDIA_PLAY); return true;
case "MEDIA_NEXT": Tap(VK_MEDIA_NEXT); return true;
case "MEDIA_PREV": Tap(VK_MEDIA_PREV); return true;
case "MEDIA_STOP": Tap(VK_MEDIA_STOP); return true;
case "BROWSER_BACK": Tap(VK_BROWSER_BACK); return true;
case "BROWSER_FORWARD": Tap(VK_BROWSER_FORWARD); return true;
// Screen dimmer overlay (default): works on any display.
case "BRIGHTNESS_UP": Dim(+_brightnessStep); return true;
case "BRIGHTNESS_DOWN": Dim(-_brightnessStep); return true;
// The monitor's actual backlight over DDC/CI, if it accepts it.
case "MONITOR_BRIGHTNESS_UP": Async(delegate { Brightness(+_brightnessStep); }); return true;
case "MONITOR_BRIGHTNESS_DOWN": Async(delegate { Brightness(-_brightnessStep); }); return true;
case "MIC_TOGGLE": Async(delegate { MicToggle(); }); return true;
case "LOCK": Async(delegate { LockWorkStation(); }); return true;
case "SLEEP": Async(delegate { Beep(600, 80); SetSuspendState(false, false, false); }); return true;
case "IGNORE": return true; // swallow the key, do nothing
default: return false;
}
}
// Only these ramp while held; everything else fires once per press.
static bool Repeats(string a) {
return a == "VOLUME_UP" || a == "VOLUME_DOWN"
|| a == "BRIGHTNESS_UP" || a == "BRIGHTNESS_DOWN"
|| a == "MONITOR_BRIGHTNESS_UP" || a == "MONITOR_BRIGHTNESS_DOWN";
}
// ------------------------------------------------------------ config
static bool TryParseKey(string s, out uint vk) {
vk = 0;
int v = NameToVk(s);
if (v < 0) {
s = s.Trim().ToUpperInvariant();
if (s.StartsWith("0X")) { try { vk = Convert.ToUInt32(s.Substring(2), 16); return true; } catch { } }
return false;
}
vk = (uint)v;
return true;
}
static int ModVk(string n) {
switch (n.Trim().ToUpperInvariant()) {
case "SHIFT": return VK_SHIFT;
case "CTRL": case "CONTROL": return VK_CONTROL;
case "ALT": case "OPTION": return VK_MENU;
case "WIN": case "CMD": case "COMMAND": return VK_LWIN;
case "NONE": return 0;
default: return -1;
}
}
static bool Down(int vk) {
if (vk == VK_LWIN)
return (GetAsyncKeyState(VK_LWIN) & 0x8000) != 0 || (GetAsyncKeyState(VK_RWIN) & 0x8000) != 0;
return (GetAsyncKeyState(vk) & 0x8000) != 0;
}
static readonly string[] DefaultIniLines = {
"# MagicVolume - Apple Magic Keyboard top row on Windows",
"#",
"# The keyboard sends its top row as plain F1..F12 and emits no media",
"# usages at all, so Windows does nothing with them. These lines put the",
"# printed keycap functions back.",
"#",
"# The keyboard's own fn key CANNOT be the modifier. fn IS transmitted",
"# (Apple vendor usage 0xFF00:0x03 inside keyboard report 1) but Windows'",
"# in-box keyboard driver only translates usage page 0x07 and throws that",
"# bit away, and the raw report is unreadable from userspace",
"# (ACCESS_DENIED - anti-keylogger protection). Only a signed kernel-mode",
"# filter driver sits low enough to see it. Use the modifier below.",
"",
"# Actions:",
"# VOLUME_UP VOLUME_DOWN MUTE MIC_TOGGLE",
"# BRIGHTNESS_UP BRIGHTNESS_DOWN (screen dimmer overlay)",
"# MONITOR_BRIGHTNESS_UP MONITOR_BRIGHTNESS_DOWN (real backlight, DDC/CI)",
"# MEDIA_PLAY MEDIA_NEXT MEDIA_PREV MEDIA_STOP",
"# BROWSER_BACK BROWSER_FORWARD",
"# LOCK SLEEP IGNORE",
"# KEYS:<combo> - send any shortcut, e.g. KEYS:WIN+TAB, KEYS:CTRL+ALT+S",
"",
"F1=BRIGHTNESS_DOWN",
"F2=BRIGHTNESS_UP",
"F3=KEYS:WIN+TAB",
"F4=KEYS:CTRL+SHIFT+S",
"F5=MIC_TOGGLE",
"F6=SLEEP",
"F7=MEDIA_PREV",
"F8=MEDIA_PLAY",
"F9=MEDIA_NEXT",
"F10=MUTE",
"F11=VOLUME_DOWN",
"F12=VOLUME_UP",
"",
"# No key sends 'lock' on this keyboard, so bind it wherever you like:",
"#F13=LOCK",
"# ...or reach it as a combo, e.g. change F6 to KEYS:WIN+L",
"",
"# Hold this to send the REAL function key instead of the action above.",
"# One of: SHIFT CTRL ALT WIN NONE",
"PassThroughModifier=SHIFT",
"",
"# Software fn-lock: toggles every remap on and off.",
"# Falling beeps = actions active. Rising beeps = plain F-keys.",
"ToggleHotkey=CTRL+ALT+F12",
"",
"# Dimmer step per press, in percent.",
"BrightnessStep=10",
"",
"# How dark F1 is allowed to go. 0 = fully black screen. Raise this to,",
"# say, 20 if you would rather not be able to black the screen out.",
"MinBrightness=0",
"",
"# BRIGHTNESS NOTE: F1/F2 draw a black, click-through, always-on-top",
"# window over every screen - 100 = no overlay, 50 = half-opacity black,",
"# 0 = fully black. It never steals clicks or focus, and F2 always brings",
"# it back, so a black screen is recoverable.",
"#",
"# To drive the monitor's REAL backlight instead, use",
"# MONITOR_BRIGHTNESS_UP/DOWN. That needs DDC/CI enabled in the monitor's",
"# own OSD menu; ActionTest.exe reports which monitors accept it."
};
static void LoadMap(string path) {
if (!File.Exists(path)) {
try { File.WriteAllLines(path, DefaultIniLines); Log("wrote default mapping.ini"); } catch { }
}
_map.Clear();
if (!File.Exists(path)) return;
foreach (string raw in File.ReadAllLines(path)) {
string line = raw.Trim();
if (line.Length == 0 || line.StartsWith("#") || line.StartsWith(";")) continue;
int eq = line.IndexOf('=');
if (eq <= 0) continue;
string name = line.Substring(0, eq).Trim();
string val = line.Substring(eq + 1).Trim();
if (name.Equals("PassThroughModifier", StringComparison.OrdinalIgnoreCase)) {
int m = ModVk(val);
if (m >= 0) { _passThroughVk = m; _passThroughName = val.ToUpperInvariant(); }
continue;
}
if (name.Equals("ToggleHotkey", StringComparison.OrdinalIgnoreCase)) { ParseToggle(val); continue; }
if (name.Equals("MinBrightness", StringComparison.OrdinalIgnoreCase)) {
int n; if (int.TryParse(val, out n) && n >= 0 && n <= 100) _minLevel = n;
continue;
}
if (name.Equals("BrightnessStep", StringComparison.OrdinalIgnoreCase)) {
int n; if (int.TryParse(val, out n) && n > 0 && n <= 100) _brightnessStep = n;
continue;
}
uint vk;
if (!TryParseKey(name, out vk)) continue;
// Preserve case after "KEYS:" so combos stay readable; upper-case the rest.
string action = val.StartsWith("KEYS:", StringComparison.OrdinalIgnoreCase)
? "KEYS:" + val.Substring(5).Trim()
: val.ToUpperInvariant();
if (action.Length > 0) _map[vk] = action;
}
foreach (var kv in _map) Log(string.Format(" map vk=0x{0:X2} -> {1}", kv.Key, kv.Value));
Log(" pass-through modifier: " + (_passThroughVk == 0 ? "NONE" : _passThroughName));
Log(" toggle hotkey: " + (_toggleVk == 0 ? "NONE" : _toggleName));
Log(" brightness step: " + _brightnessStep + "%");
}
static void ParseToggle(string spec) {
_toggleVk = 0; _toggleMods = new int[0]; _toggleName = "";
if (spec.Length == 0 || spec.Equals("NONE", StringComparison.OrdinalIgnoreCase)) return;
var mods = new List<int>();
uint key = 0;
foreach (string p in spec.Split('+')) {
string t = p.Trim();
if (t.Length == 0) continue;
if (IsModName(t)) { mods.Add(ModVk(t)); continue; }
uint vk;
if (TryParseKey(t, out vk)) key = vk;
}
if (key == 0) return;
_toggleVk = key; _toggleMods = mods.ToArray(); _toggleName = spec.ToUpperInvariant();
}
// ------------------------------------------------------------ hook
static IntPtr Hook(int code, IntPtr wParam, IntPtr lParam) {
if (code < 0) return CallNextHookEx(_hook, code, wParam, lParam);
var k = (KBDLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(KBDLLHOOKSTRUCT));
// Never re-process the keystrokes we synthesise ourselves.
if ((k.flags & (LLKHF_INJECTED | LLKHF_LOWER_IL_INJECTED)) != 0)
return CallNextHookEx(_hook, code, wParam, lParam);
int msg = wParam.ToInt32();
bool isDown = (msg == WM_KEYDOWN || msg == WM_SYSKEYDOWN);
bool isUp = (msg == WM_KEYUP || msg == WM_SYSKEYUP);
if (_toggleVk != 0 && k.vkCode == _toggleVk) {
bool allMods = true;
foreach (int m in _toggleMods) if (!Down(m)) { allMods = false; break; }
if (allMods) {
if (isDown && !_held.Contains(k.vkCode)) {
_held.Add(k.vkCode);
_enabled = !_enabled;
Log("toggled: " + (_enabled ? "ON (mac keys)" : "OFF (plain F-keys)"));
if (_enabled) { Beep(700, 70); Beep(500, 70); }
else { Beep(500, 70); Beep(700, 70); }
}
if (isUp) _held.Remove(k.vkCode);
return new IntPtr(1);
}
}
if (!_enabled) return CallNextHookEx(_hook, code, wParam, lParam);
string action;
if (!_map.TryGetValue(k.vkCode, out action))
return CallNextHookEx(_hook, code, wParam, lParam);
// Escape hatch for a genuine F-key. (Cannot be fn - see header.)
if (_passThroughVk != 0 && Down(_passThroughVk)) {
_held.Remove(k.vkCode);
return CallNextHookEx(_hook, code, wParam, lParam);
}
// Ctrl/Alt/Win + F-key are application shortcuts - Alt+F4 closes a
// window, Ctrl+F5 hard-reloads, and so on. Stealing those would break
// far more than the remap is worth, so only a BARE F-key acts.
if (Down(VK_CONTROL) || Down(VK_MENU) || Down(VK_LWIN)) {
_held.Remove(k.vkCode);
return CallNextHookEx(_hook, code, wParam, lParam);
}
if (isUp) { _held.Remove(k.vkCode); return new IntPtr(1); }
if (isDown) {
bool repeat = _held.Contains(k.vkCode);
if (!repeat) _held.Add(k.vkCode);
if (!repeat || Repeats(action)) {
if (!Fire(action)) Log("unknown action: " + action);
}
return new IntPtr(1);
}
return CallNextHookEx(_hook, code, wParam, lParam);
}
static int _rehookFails = 0;
static void Rehook() {
IntPtr fresh = SetWindowsHookEx(WH_KEYBOARD_LL, _proc, GetModuleHandle(null), 0);
if (fresh == IntPtr.Zero) {
if (_rehookFails++ == 0) Log("rehook failed " + Marshal.GetLastWin32Error() + " (keeping old hook)");
return;
}
IntPtr old = _hook;
_hook = fresh; // new hook is installed first, so no gap in coverage
UnhookWindowsHookEx(old); // fails harmlessly if Windows already dropped it
_rehookFails = 0;
}
[STAThread]
static void Main(string[] args) {
string dir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
_logPath = Path.Combine(dir, "magicvolume.log");
bool created;
using (var mutex = new Mutex(true, "MagicVolume.SingleInstance", out created)) {
if (!created) { Log("already running; exiting"); return; }
LoadMap(Path.Combine(dir, "mapping.ini"));
if (_map.Count == 0) { Log("no mappings; exiting"); return; }
var ot = new Thread(OverlayThread);
ot.IsBackground = true;
ot.SetApartmentState(ApartmentState.STA);
ot.Start();
_proc = Hook;
_hook = SetWindowsHookEx(WH_KEYBOARD_LL, _proc, GetModuleHandle(null), 0);
if (_hook == IntPtr.Zero) { Log("SetWindowsHookEx failed " + Marshal.GetLastWin32Error()); return; }
Log("MagicVolume running");
// Windows silently removes a WH_KEYBOARD_LL hook whose callback ever
// stalls past LowLevelHooksTimeout, and never tells the process. The
// process then sits there alive but doing nothing. Re-install the hook
// every 60 s so a dropped hook heals itself instead of needing restart.ps1.
SetTimer(IntPtr.Zero, UIntPtr.Zero, 60000, IntPtr.Zero);
MSG m;
while (GetMessageW(out m, IntPtr.Zero, 0, 0) > 0) {
if (m.message == WM_TIMER) Rehook();
}
UnhookWindowsHookEx(_hook);
}
}
}