-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
1338 lines (1151 loc) · 43.7 KB
/
Copy pathProgram.cs
File metadata and controls
1338 lines (1151 loc) · 43.7 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
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
namespace MeetMicSync;
internal static class Program
{
[STAThread]
private static void Main()
{
Application.SetHighDpiMode(HighDpiMode.SystemAware);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
using var app = new SyncApplication();
Application.Run(app.Context);
}
}
internal static class Log
{
private static readonly object Gate = new();
private static readonly string Dir = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"MeetMicSync");
private static readonly string LogPath = Path.Combine(Dir, "log.txt");
private static readonly string SettingsPath = Path.Combine(Dir, "settings.ini");
private static bool _enabled;
public static string FilePath => LogPath;
public static bool Enabled
{
get { lock (Gate) return _enabled; }
set
{
lock (Gate)
{
if (_enabled == value)
return;
_enabled = value;
SaveSettings();
if (_enabled)
{
Directory.CreateDirectory(Dir);
File.AppendAllText(LogPath,
$"--- logging enabled {DateTime.Now:O} ---{Environment.NewLine}");
}
}
}
}
static Log()
{
_enabled = LoadEnabled();
}
public static void Write(string message)
{
if (!_enabled)
return;
var line = $"{DateTime.Now:HH:mm:ss.fff} {message}";
lock (Gate)
{
if (!_enabled)
return;
Directory.CreateDirectory(Dir);
File.AppendAllText(LogPath, line + Environment.NewLine);
}
Debug.WriteLine(line);
}
private static bool LoadEnabled()
{
try
{
if (!File.Exists(SettingsPath))
return false;
foreach (var raw in File.ReadAllLines(SettingsPath))
{
var line = raw.Trim();
if (line.StartsWith("Logging=", StringComparison.OrdinalIgnoreCase))
return line.Equals("Logging=1", StringComparison.OrdinalIgnoreCase)
|| line.Equals("Logging=true", StringComparison.OrdinalIgnoreCase);
}
}
catch { /* default off */ }
return false;
}
private static void SaveSettings()
{
try
{
Directory.CreateDirectory(Dir);
File.WriteAllText(SettingsPath, $"Logging={(_enabled ? "1" : "0")}{Environment.NewLine}");
}
catch { /* ignore */ }
}
}
internal sealed class SyncApplication : IDisposable
{
private readonly NotifyIcon _tray;
private readonly MeetMuteSender _sender = new();
private readonly MicMuteWatcher _micWatcher;
private readonly LenovoOsdWatcher _osdWatcher;
private readonly object _gate = new();
private long _lastActionTicks;
private bool? _lastMuted;
private static readonly long DebounceTicks = TimeSpan.FromMilliseconds(400).Ticks;
public ApplicationContext Context { get; }
public SyncApplication()
{
_micWatcher = new MicMuteWatcher(OnMicMuteChanged, OnCaptureDeviceStateChanged);
_osdWatcher = new LenovoOsdWatcher(OnLenovoOsd);
_tray = new NotifyIcon
{
Text = "Meet Mic Sync",
Icon = SystemIcons.Application,
Visible = true,
ContextMenuStrip = BuildMenu()
};
Context = new ApplicationContext();
var micOk = _micWatcher.Start();
var osdOk = _osdWatcher.Start();
Log.Write($"micWatcher={micOk} osdWatcher={osdOk}");
SetTray(micOk || osdOk
? "Meet Mic Sync — listening (mic+OSD)"
: "Meet Mic Sync — failed to start watchers");
if (!AppInstall.StartupShortcutExists())
{
_tray.ShowBalloonTip(
5000,
"Meet Mic Sync",
"Tip: right-click this icon → “Start with Windows…” to run automatically at sign-in.",
ToolTipIcon.Info);
}
}
private ContextMenuStrip BuildMenu()
{
var menu = new ContextMenuStrip();
menu.Items.Add("Test Meet mute (Ctrl+D)", null, (_, _) =>
{
var ok = _sender.TrySyncMeetMute(wantMuted: null, out var detail);
Log.Write($"TEST toggle ok={ok} detail={detail}");
SetTray(ok ? $"Test OK → {detail}" : "Test FAIL — Meet window not found");
_tray.ShowBalloonTip(2000, "Meet Mic Sync",
ok ? $"Toggled Meet: {detail}" : "Meet window not found. Open a Meet tab.",
ok ? ToolTipIcon.Info : ToolTipIcon.Warning);
});
menu.Items.Add(new ToolStripSeparator());
var startupItem = new ToolStripMenuItem();
void RefreshStartupItem()
{
if (AppInstall.StartupShortcutExists())
{
startupItem.Text = "Remove from Windows Startup…";
startupItem.Click -= OnEnableStartupClick;
startupItem.Click -= OnDisableStartupClick;
startupItem.Click += OnDisableStartupClick;
}
else
{
startupItem.Text = "Start with Windows…";
startupItem.Click -= OnEnableStartupClick;
startupItem.Click -= OnDisableStartupClick;
startupItem.Click += OnEnableStartupClick;
}
}
RefreshStartupItem();
menu.Opening += (_, _) => RefreshStartupItem();
menu.Items.Add(startupItem);
menu.Items.Add("Open log", null, (_, _) =>
{
try
{
if (!File.Exists(Log.FilePath))
{
MessageBox.Show(
"No log file yet.\n\nEnable logging from the tray menu first, then reproduce the issue.",
"Meet Mic Sync",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
return;
}
Process.Start(new ProcessStartInfo("explorer.exe", $"/select,\"{Log.FilePath}\"")
{
UseShellExecute = true
});
}
catch (Exception ex)
{
Log.Write($"open log failed: {ex.Message}");
}
});
var loggingItem = new ToolStripMenuItem();
void RefreshLoggingItem()
{
loggingItem.Text = Log.Enabled ? "Disable logging" : "Enable logging";
}
RefreshLoggingItem();
loggingItem.Click += (_, _) =>
{
Log.Enabled = !Log.Enabled;
RefreshLoggingItem();
_tray.ShowBalloonTip(
2000,
"Meet Mic Sync",
Log.Enabled ? "Logging enabled." : "Logging disabled.",
ToolTipIcon.Info);
};
menu.Opening += (_, _) => RefreshLoggingItem();
menu.Items.Add(loggingItem);
menu.Items.Add("Exit", null, (_, _) =>
{
_tray.Visible = false;
Application.Exit();
});
return menu;
}
private void OnEnableStartupClick(object? sender, EventArgs e)
{
var answer = MessageBox.Show(
AppInstall.BuildConfirmMessage(),
"Start Meet Mic Sync with Windows?",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question,
MessageBoxDefaultButton.Button2);
if (answer != DialogResult.Yes)
{
Log.Write("install: user cancelled Enable Startup");
return;
}
var result = AppInstall.EnableStartup();
if (!result.Success)
{
MessageBox.Show(result.Message, "Meet Mic Sync", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (result.NeedsRestart)
{
MessageBox.Show(
result.Message,
"Meet Mic Sync",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
try
{
AppInstall.RestartFromInstalledCopy();
}
catch (Exception ex)
{
Log.Write($"restart from install dir failed: {ex.Message}");
MessageBox.Show(
"The Startup shortcut was created, but the app could not restart from the new folder automatically.\n\n" +
$"Please run:\n{AppInstall.InstalledExePath}",
"Meet Mic Sync",
MessageBoxButtons.OK,
MessageBoxIcon.Warning);
return;
}
_tray.Visible = false;
Application.Exit();
return;
}
MessageBox.Show(result.Message, "Meet Mic Sync", MessageBoxButtons.OK, MessageBoxIcon.Information);
_tray.ShowBalloonTip(2500, "Meet Mic Sync", "Will start automatically when you sign in.", ToolTipIcon.Info);
}
private void OnDisableStartupClick(object? sender, EventArgs e)
{
var answer = MessageBox.Show(
AppInstall.BuildRemoveConfirmMessage(),
"Remove from Windows Startup?",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question,
MessageBoxDefaultButton.Button2);
if (answer != DialogResult.Yes)
{
Log.Write("install: user cancelled Remove Startup");
return;
}
var result = AppInstall.DisableStartup();
MessageBox.Show(
result.Message,
"Meet Mic Sync",
MessageBoxButtons.OK,
result.Success ? MessageBoxIcon.Information : MessageBoxIcon.Error);
}
private void OnMicMuteChanged(bool muted)
{
lock (_gate)
{
if (_lastMuted is null)
{
_lastMuted = muted;
Log.Write($"mic seed muted={muted}");
return;
}
if (_lastMuted == muted)
return;
_lastMuted = muted;
Log.Write($"mic mute changed → muted={muted}");
}
TriggerFrom("mic-mute", muted ? "muted" : "unmuted", wantMuted: muted);
}
private void OnLenovoOsd(string info)
{
Log.Write($"lenovo OSD/event: {info}");
// OSD often arrives after mic-mute (debounced). If it arrives alone, use last known mic state.
bool? want = null;
lock (_gate) { want = _lastMuted; }
TriggerFrom("lenovo-osd", info, wantMuted: want);
}
private void OnCaptureDeviceStateChanged(string deviceId, int newState)
{
// 1=ACTIVE 2=DISABLED 4=NOTPRESENT 8=UNPLUGGED
Log.Write($"capture device state id={deviceId} state={newState}");
// Lenovo hardware mute often disables the endpoint instead of soft-mute.
if (newState is 1 or 2 or 8)
{
// ACTIVE → want unmuted; DISABLED/UNPLUGGED → want muted
bool wantMuted = newState != 1;
TriggerFrom("device-state", $"state={newState}", wantMuted: wantMuted);
}
}
private void TriggerFrom(string source, string info, bool? wantMuted)
{
lock (_gate)
{
var now = Stopwatch.GetTimestamp();
if (now - _lastActionTicks < DebounceTicks)
{
Log.Write($"debounce skip ({source})");
return;
}
_lastActionTicks = now;
}
// Audio/OSD callbacks are NOT on the UI thread. SendInput from a
// background thread is ignored by Chrome — always marshal first.
void Run()
{
var ok = _sender.TrySyncMeetMute(wantMuted, out var detail);
Log.Write($"sync after {source} ({info}) wantMuted={wantMuted}: ok={ok} detail={detail}");
SetTray(ok
? $"Synced via {source} → {detail}"
: $"Saw {source}, but Meet sync failed");
}
var menu = _tray.ContextMenuStrip;
if (menu is { IsHandleCreated: true } && menu.InvokeRequired)
menu.BeginInvoke(Run);
else
Run();
}
private void SetTray(string text)
{
void Apply() => _tray.Text = text.Length <= 63 ? text : text[..63];
try
{
if (_tray.ContextMenuStrip?.InvokeRequired == true)
_tray.ContextMenuStrip.BeginInvoke(Apply);
else
Apply();
}
catch
{
Apply();
}
}
public void Dispose()
{
_osdWatcher.Dispose();
_micWatcher.Dispose();
_tray.Dispose();
}
}
/// <summary>
/// Core Audio mute + device-state callbacks — zero polling while idle.
/// Subscribes to every active capture endpoint (not only the default).
/// </summary>
internal sealed class MicMuteWatcher : IDisposable
{
private readonly Action<bool> _onMuteChanged;
private readonly Action<string, int> _onDeviceStateChanged;
private readonly List<EndpointSubscription> _subscriptions = new();
private readonly DeviceNotificationClient _deviceClient;
private IMMDeviceEnumerator? _enumerator;
private bool _seeded;
private sealed class EndpointSubscription
{
public required string Id;
public required IMMDevice Device;
public required IAudioEndpointVolume Volume;
public required VolumeCallback Callback;
}
public MicMuteWatcher(Action<bool> onMuteChanged, Action<string, int> onDeviceStateChanged)
{
_onMuteChanged = onMuteChanged;
_onDeviceStateChanged = onDeviceStateChanged;
_deviceClient = new DeviceNotificationClient(
OnDefaultDeviceChanged,
OnAnyDeviceStateChanged);
}
public bool Start()
{
try
{
_enumerator = (IMMDeviceEnumerator)new MMDeviceEnumeratorComObject();
_enumerator.RegisterEndpointNotificationCallback(_deviceClient);
var n = AttachAllCaptureEndpoints();
Log.Write($"mic: subscribed endpoints={n}");
return n > 0;
}
catch (Exception ex)
{
Log.Write($"mic Start exception: {ex}");
return false;
}
}
private void OnDefaultDeviceChanged()
{
Log.Write("mic: default capture device changed — resubscribing");
try
{
DetachAll();
AttachAllCaptureEndpoints();
}
catch (Exception ex)
{
Log.Write($"mic reattach failed: {ex.Message}");
}
}
private void OnAnyDeviceStateChanged(string deviceId, int newState)
{
// Capture endpoints use {0.0.1....}; render uses {0.0.0....}.
if (deviceId.IndexOf("{0.0.1.", StringComparison.OrdinalIgnoreCase) < 0)
return;
Log.Write($"mic: OnDeviceStateChanged id={deviceId} state={newState}");
_onDeviceStateChanged(deviceId, newState);
try
{
DetachAll();
AttachAllCaptureEndpoints();
}
catch (Exception ex)
{
Log.Write($"mic state-change reattach failed: {ex.Message}");
}
}
private int AttachAllCaptureEndpoints()
{
if (_enumerator is null)
return 0;
// 0x1 = DEVICE_STATE_ACTIVE only for mute subscription; state callback covers disable.
var hr = _enumerator.EnumAudioEndpoints(EDataFlow.eCapture, 0x1, out var collPtr);
if (hr != 0 || collPtr == IntPtr.Zero)
{
Log.Write($"mic: EnumAudioEndpoints hr=0x{hr:X8}");
return AttachDefaultFallback();
}
var coll = (IMMDeviceCollection)Marshal.GetObjectForIUnknown(collPtr);
Marshal.Release(collPtr);
coll.GetCount(out var count);
var attached = 0;
for (uint i = 0; i < count; i++)
{
coll.Item(i, out var device);
if (device is null) continue;
if (TrySubscribe(device))
attached++;
else
Marshal.ReleaseComObject(device);
}
Marshal.ReleaseComObject(coll);
return attached > 0 ? attached : AttachDefaultFallback();
}
private int AttachDefaultFallback()
{
if (_enumerator is null) return 0;
var hr = _enumerator.GetDefaultAudioEndpoint(EDataFlow.eCapture, ERole.eCommunications, out var device);
if (hr != 0 || device is null)
hr = _enumerator.GetDefaultAudioEndpoint(EDataFlow.eCapture, ERole.eConsole, out device);
if (hr != 0 || device is null) return 0;
return TrySubscribe(device) ? 1 : 0;
}
private bool TrySubscribe(IMMDevice device)
{
device.GetId(out var id);
device.GetState(out var state);
var iid = typeof(IAudioEndpointVolume).GUID;
var actHr = device.Activate(ref iid, ClsCtx.ALL, IntPtr.Zero, out var obj);
if (actHr != 0 || obj is null)
{
Log.Write($"mic: Activate failed id={id} hr=0x{actHr:X8}");
return false;
}
var volume = (IAudioEndpointVolume)obj;
var callback = new VolumeCallback(muted =>
{
Log.Write($"mic notify id={id} muted={muted}");
_onMuteChanged(muted);
});
var regHr = volume.RegisterControlChangeNotify(callback);
Log.Write($"mic: attach id={id} state={state} reg=0x{regHr:X8}");
if (regHr != 0)
{
Marshal.ReleaseComObject(volume);
return false;
}
_subscriptions.Add(new EndpointSubscription
{
Id = id,
Device = device,
Volume = volume,
Callback = callback
});
volume.GetMute(out var muted);
if (!_seeded)
{
_seeded = true;
_onMuteChanged(muted != 0);
}
return true;
}
private void DetachAll()
{
foreach (var s in _subscriptions)
{
try { s.Volume.UnregisterControlChangeNotify(s.Callback); } catch { /* ignore */ }
Marshal.ReleaseComObject(s.Volume);
Marshal.ReleaseComObject(s.Device);
}
_subscriptions.Clear();
}
public void Dispose()
{
DetachAll();
if (_enumerator is not null)
{
try { _enumerator.UnregisterEndpointNotificationCallback(_deviceClient); } catch { /* ignore */ }
Marshal.ReleaseComObject(_enumerator);
_enumerator = null;
}
}
}
/// <summary>
/// Watches Lenovo FnHotkeyUtility / Vantage OSD appearing via WinEvent
/// (EVENT_OBJECT_SHOW). Event-driven — no timers.
/// </summary>
internal sealed class LenovoOsdWatcher : IDisposable
{
private readonly Action<string> _onOsd;
private readonly List<IntPtr> _hooks = new();
private WinEventDelegate? _proc; // keep alive
private const uint EVENT_SYSTEM_DIALOGSTART = 0x0010;
private const uint EVENT_OBJECT_SHOW = 0x8002;
private const uint EVENT_OBJECT_UNCLOAKED = 0x8018;
private const uint WINEVENT_OUTOFCONTEXT = 0x0000;
private const int OBJID_WINDOW = 0;
public LenovoOsdWatcher(Action<string> onOsd) => _onOsd = onOsd;
public bool Start()
{
_proc = WinEventProc;
// Narrow event set only — still fully event-driven (no timers).
foreach (var ev in new[] { EVENT_OBJECT_SHOW, EVENT_OBJECT_UNCLOAKED, EVENT_SYSTEM_DIALOGSTART })
{
var hook = SetWinEventHook(ev, ev, IntPtr.Zero, _proc, 0, 0, WINEVENT_OUTOFCONTEXT);
if (hook != IntPtr.Zero)
_hooks.Add(hook);
Log.Write($"osd: hook event=0x{ev:X} handle=0x{hook:X}");
}
return _hooks.Count > 0;
}
private void WinEventProc(
IntPtr hWinEventHook, uint eventType, IntPtr hwnd,
int idObject, int idChild, uint dwEventThread, uint dwmsEventTime)
{
if (hwnd == IntPtr.Zero || idObject != OBJID_WINDOW || idChild != 0)
return;
try
{
if (!IsWindowVisible(hwnd))
return;
_ = GetWindowThreadProcessId(hwnd, out var pid);
string processName;
try
{
using var p = Process.GetProcessById((int)pid);
processName = p.ProcessName;
}
catch
{
return;
}
if (!IsLenovoHotkeyProcess(processName))
return;
var className = GetClass(hwnd);
var title = GetTitle(hwnd);
// Skip IME / infrastructure windows.
if (className is "IME" or "MSCTFIME UI" ||
className.Contains("BroadcastEvent", StringComparison.OrdinalIgnoreCase) ||
className.Contains("GDI+", StringComparison.OrdinalIgnoreCase))
return;
// FnHotkeyUtility often uses dialog (#32770) or custom OSD classes.
var info = $"evt=0x{eventType:X} proc={processName} class={className} title={title} hwnd=0x{hwnd:X}";
_onOsd(info);
}
catch (Exception ex)
{
Log.Write($"osd proc error: {ex.Message}");
}
}
private static bool IsLenovoHotkeyProcess(string name) =>
name.Contains("FnHotkey", StringComparison.OrdinalIgnoreCase) ||
name.Contains("LenovoUtility", StringComparison.OrdinalIgnoreCase) ||
name.Equals("LenovoVantage", StringComparison.OrdinalIgnoreCase) ||
name.Contains("LenovoVantage", StringComparison.OrdinalIgnoreCase) ||
name.Contains("ImController", StringComparison.OrdinalIgnoreCase);
private static string GetClass(IntPtr hwnd)
{
var sb = new StringBuilder(256);
_ = GetClassName(hwnd, sb, sb.Capacity);
return sb.ToString();
}
private static string GetTitle(IntPtr hwnd)
{
var len = GetWindowTextLength(hwnd);
if (len <= 0) return "";
var sb = new StringBuilder(len + 1);
_ = GetWindowText(hwnd, sb, sb.Capacity);
return sb.ToString();
}
public void Dispose()
{
foreach (var hook in _hooks)
UnhookWinEvent(hook);
_hooks.Clear();
_proc = null;
}
private delegate void WinEventDelegate(
IntPtr hWinEventHook, uint eventType, IntPtr hwnd,
int idObject, int idChild, uint dwEventThread, uint dwmsEventTime);
[DllImport("user32.dll")]
private static extern IntPtr SetWinEventHook(
uint eventMin, uint eventMax, IntPtr hmodWinEventProc,
WinEventDelegate lpfnWinEventProc, uint idProcess, uint idThread, uint dwFlags);
[DllImport("user32.dll")]
private static extern bool UnhookWinEvent(IntPtr hWinEventHook);
[DllImport("user32.dll")]
private static extern bool IsWindowVisible(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
[DllImport("user32.dll")]
private static extern int GetWindowTextLength(IntPtr hWnd);
}
internal sealed class VolumeCallback : IAudioEndpointVolumeCallback
{
private readonly Action<bool> _onMute;
public VolumeCallback(Action<bool> onMute) => _onMute = onMute;
public int OnNotify(IntPtr pNotify)
{
if (pNotify == IntPtr.Zero) return 0;
var data = Marshal.PtrToStructure<AudioVolumeNotificationData>(pNotify)!;
_onMute(data.bMuted != 0);
return 0;
}
}
internal sealed class DeviceNotificationClient : IMMNotificationClient
{
private readonly Action _onDefaultCaptureChanged;
private readonly Action<string, int> _onDeviceStateChanged;
public DeviceNotificationClient(Action onDefaultCaptureChanged, Action<string, int> onDeviceStateChanged)
{
_onDefaultCaptureChanged = onDefaultCaptureChanged;
_onDeviceStateChanged = onDeviceStateChanged;
}
public void OnDefaultDeviceChanged(EDataFlow flow, ERole role, string deviceId)
{
if (flow == EDataFlow.eCapture)
_onDefaultCaptureChanged();
}
public void OnDeviceAdded(string deviceId) { }
public void OnDeviceRemoved(string deviceId) { }
public void OnDeviceStateChanged(string deviceId, int newState)
=> _onDeviceStateChanged(deviceId, newState);
public void OnPropertyValueChanged(string deviceId, PropertyKey key) { }
}
internal sealed class MeetMuteSender
{
/// <param name="wantMuted">
/// true = make sure Meet is muted; false = unmuted; null = toggle (test menu).
/// </param>
public bool TrySyncMeetMute(bool? wantMuted, out string detail)
{
detail = "";
if (!TryFindMeetWindow(out var hwnd, out detail))
{
Log.Write("Meet window not found. Browser titles:");
LogBrowserTitles();
return false;
}
// State-based UIA: click only the toolbar button that achieves the desired state.
// Blind toggle caused "unmute works, mute doesn't" when Meet/Windows drifted apart.
if (wantMuted is bool desired)
{
var action = TryApplyMeetMuteState(hwnd, desired, out var via);
detail += $" [{via}]";
Log.Write($"Meet sync wantMuted={desired}: {via}");
return action;
}
// Explicit toggle (tray test): Ctrl+D first, then UIA flip of whichever self-button is shown.
if (EnsureForeground(hwnd))
{
Thread.Sleep(40);
SendCtrlD();
detail += " [Ctrl+D]";
Log.Write("Meet toggle via Ctrl+D");
return true;
}
if (TryClickEitherSelfMute(hwnd, out var toggleVia))
{
detail += $" [{toggleVia}]";
return true;
}
SendCtrlD();
detail += " [Ctrl+D-nofocus]";
return true;
}
private static bool TryApplyMeetMuteState(IntPtr hwnd, bool wantMuted, out string via)
{
// Labels that appear when Meet is currently UNMUTED (click → mute).
string[] muteLabels =
[
"Turn off microphone",
"Выключить микрофон",
"Mikrofon ausschalten"
];
// Labels that appear when Meet is currently MUTED (click → unmute).
string[] unmuteLabels =
[
"Turn on microphone",
"Включить микрофон",
"Mikrofon einschalten"
];
var needClick = wantMuted ? muteLabels : unmuteLabels;
var alreadyOk = wantMuted ? unmuteLabels : muteLabels;
if (TryClickToolbarButton(hwnd, needClick, out var clicked))
{
via = wantMuted ? $"mute:{clicked}" : $"unmute:{clicked}";
return true;
}
if (FindToolbarButton(hwnd, alreadyOk, out var present))
{
// Desired state already reflected in Meet UI — do not toggle.
via = $"already-{(wantMuted ? "muted" : "unmuted")}:{present}";
return true;
}
// Unknown UI — fall back to Ctrl+D (may desync if Meet state unknown).
Log.Write("UIA did not see expected self-mute labels — Ctrl+D fallback");
if (!EnsureForeground(hwnd))
Log.Write("WARNING: SetForegroundWindow did not stick — Ctrl+D may miss");
Thread.Sleep(40);
SendCtrlD();
via = "Ctrl+D-fallback";
return true;
}
private static bool TryClickEitherSelfMute(IntPtr hwnd, out string via)
{
string[] all =
[
"Turn off microphone", "Turn on microphone",
"Выключить микрофон", "Включить микрофон",
"Mikrofon ausschalten", "Mikrofon einschalten"
];
if (TryClickToolbarButton(hwnd, all, out var name))
{
via = $"UIA-toggle:{name}";
return true;
}
via = "";
return false;
}
private static bool TryClickToolbarButton(IntPtr hwnd, string[] names, out string clickedName)
{
clickedName = "";
if (!FindToolbarButton(hwnd, names, out var el, out clickedName) || el is null)
return false;
try
{
if (el.TryGetCurrentPattern(System.Windows.Automation.InvokePattern.Pattern, out var pattern) &&
pattern is System.Windows.Automation.InvokePattern invoke)
{
invoke.Invoke();
return true;
}
}
catch (Exception ex)
{
Log.Write($"UIA invoke error: {ex.Message}");
}
return false;
}
private static bool FindToolbarButton(IntPtr hwnd, string[] names, out string foundName)
=> FindToolbarButton(hwnd, names, out _, out foundName);
private static bool FindToolbarButton(
IntPtr hwnd,
string[] names,
out System.Windows.Automation.AutomationElement? element,
out string foundName)
{
element = null;
foundName = "";
try
{
var root = System.Windows.Automation.AutomationElement.FromHandle(hwnd);
if (root is null)
return false;
System.Windows.Rect windowRect;
try { windowRect = root.Current.BoundingRectangle; }
catch { return false; }
if (windowRect.IsEmpty || windowRect.Height <= 0)
return false;
// Only consider controls in the bottom toolbar band.
var toolbarTop = windowRect.Top + windowRect.Height * 0.72;
System.Windows.Automation.AutomationElement? best = null;
var bestBottom = double.MinValue;
var bestName = "";
foreach (var name in names)
{
var cond = new System.Windows.Automation.AndCondition(
new System.Windows.Automation.PropertyCondition(
System.Windows.Automation.AutomationElement.NameProperty, name),
new System.Windows.Automation.PropertyCondition(
System.Windows.Automation.AutomationElement.ControlTypeProperty,
System.Windows.Automation.ControlType.Button));
var matches = root.FindAll(System.Windows.Automation.TreeScope.Descendants, cond);
foreach (System.Windows.Automation.AutomationElement el in matches)
{
try
{
if (el.Current.IsOffscreen)
continue;
if (!el.Current.IsEnabled)
continue;
var rect = el.Current.BoundingRectangle;
if (rect.IsEmpty || rect.Width <= 0 || rect.Height <= 0)
continue;
if (rect.Top < toolbarTop)
continue;
if (rect.Bottom >= bestBottom)
{
bestBottom = rect.Bottom;
best = el;
bestName = name;
}
}
catch { /* stale UIA node */ }
}
}
if (best is null)
return false;
element = best;
foundName = bestName;
return true;
}
catch (Exception ex)
{
Log.Write($"UIA find error: {ex.GetType().Name}: {ex.Message}");
return false;
}
}
private static void LogBrowserTitles()
{