-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathForm1.cs
More file actions
522 lines (426 loc) · 12.5 KB
/
Copy pathForm1.cs
File metadata and controls
522 lines (426 loc) · 12.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
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Timers;
using System.Windows.Forms;
using Gma.System.MouseKeyHook;
using Microsoft.Win32;
namespace StealthNotes
{
public partial class Form1 : Form
{
[DllImport("User32.dll")]
public static extern IntPtr GetDC(IntPtr hwnd);
[DllImport("User32.dll")]
public static extern void ReleaseDC(IntPtr hwnd, IntPtr dc);
private const string version = "v0.7";
private InputDevices inputs;
private Config config;
private bool isMuted = false;
private EnhancedTimer unmuteTimer;
private EnhancedTimer refreshDevicesTimer;
private Color defaultCellBgColor = Color.White;
private bool reloadDevicesOnNextUnmute = false;
private Rectangle alertRectangle1 = new Rectangle(0, 0, 240, 240);
private Rectangle alertRectangle2 = new Rectangle(240, 240, 240, 240);
private Rectangle activeRectangle = new Rectangle(0, 0, 240, 240);
private IKeyboardMouseEvents m_GlobalHook;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Icon = Properties.Resources.MicOn;
notifyIcon1.Icon = Properties.Resources.MicOn;
Text = $"Stealth Notes {version}";
config = new Config().Load();
SetupUnmuteTimer(config.MuteIntervalMs);
SetupRefreshDevicesTimer();
tbMuteInterval.Value = config.MuteIntervalMs;
SetNewInterval(config.MuteIntervalMs);
InitGrid();
SetupKeyboardHook();
chkIgnoreModifierKeys.Checked = config.IgnoreModifierKeys;
SetRefreshDevicesButton();
chkStartMinimized.Checked = config.StartMinimized;
if (chkStartMinimized.Checked)
WindowState = FormWindowState.Minimized;
}
private void SetRefreshDevicesButton()
{
btnReloadDevices.Font = new Font("Wingdings 3", 12, FontStyle.Bold);
btnReloadDevices.Text = char.ConvertFromUtf32(81); // or 80
btnReloadDevices.Width = 40;
btnReloadDevices.Height = 40;
}
private void SetupKeyboardHook()
{
m_GlobalHook = Hook.GlobalEvents();
m_GlobalHook.KeyDown += GlobalHookKeyPress;
}
private static List<Keys> ignoreKeycodes = new List<Keys> { Keys.LMenu, Keys.LControlKey, Keys.LWin, Keys.RMenu, Keys.RControlKey, Keys.RWin, Keys.LShiftKey, Keys.RShiftKey };
private static List<Keys> ignoreModifiers = new List<Keys> { Keys.Control, Keys.Alt, Keys.Shift };
private void GlobalHookKeyPress(object sender, KeyEventArgs e)
{
if (config.IgnoreModifierKeys)
{
if (ignoreKeycodes.Any(kc => e.KeyCode.HasFlag(kc)))
return;
if (ignoreModifiers.Any(m => e.Modifiers.HasFlag(m)))
return;
}
// don't mute mic/show visual alert if we're not currently using any inputs
if (!IsInUseByApplication())
return;
ShowAlert();
if (!isMuted && !SelectedItemsAreMuted())
{
isMuted = true;
MuteSelectedItems();
notifyIcon1.Icon = Properties.Resources.MicOff;
if (InvokeRequired)
Invoke(new MethodInvoker(delegate { Icon = Properties.Resources.MicOff; }));
else
Icon = Properties.Resources.MicOff;
}
if (isMuted)
unmuteTimer.Restart();
}
private bool SelectedItemsAreMuted()
{
if (GetSelectedItemNames().Any(name => !inputs.IsMutedByName(name)))
return false;
return true;
}
private void ShowAlert()
{
IntPtr desktopPtr = GetDC(IntPtr.Zero);
Graphics g = Graphics.FromHdc(desktopPtr);
SolidBrush b = new SolidBrush(Color.DeepPink);
InvalidateRect(IntPtr.Zero, activeRectangle, true);
activeRectangle = activeRectangle == alertRectangle1 ? alertRectangle2 : alertRectangle1;
g.FillRectangle(b, activeRectangle);
g.Dispose();
ReleaseDC(IntPtr.Zero, desktopPtr);
}
private void InitGrid()
{
inputs = new InputDevices();
PopulateGrid();
}
private void PopulateGrid()
{
foreach (var deviceName in inputs.DeviceNames)
{
var input = inputs.GetInputByName(deviceName);
var selected = config.DevicesToMute.Contains(input.FriendlyName);
var name = input.FriendlyName;
var muted = input.AudioEndpointVolume.Mute;
var rowIdx = dgvInputs.Rows.Add(selected, name, muted);
var row = dgvInputs.Rows[rowIdx];
row.Cells[(int)DeviceGridColumns.Muted].Value = muted;
row.Cells[(int)DeviceGridColumns.Name].Style.BackColor = muted ? Color.LightPink : defaultCellBgColor;
}
}
private void SetupUnmuteTimer(int intervalSeconds)
{
unmuteTimer = new EnhancedTimer(config.MuteIntervalMs * 1000);
unmuteTimer.Elapsed += OnUnmuteTimedEvent;
unmuteTimer.AutoReset = false;
unmuteTimer.Enabled = true;
unmuteTimer.Interval = intervalSeconds * 1000;
}
private void SetupRefreshDevicesTimer()
{
var refreshIntervalMinutes = 5;
refreshDevicesTimer = new EnhancedTimer(config.MuteIntervalMs * 1000);
refreshDevicesTimer.Elapsed += OnRefreshDevicesTimedEvent;
refreshDevicesTimer.AutoReset = true;
refreshDevicesTimer.Enabled = true;
refreshDevicesTimer.Interval = refreshIntervalMinutes * 60 * 1000;
}
private void OnUnmuteTimedEvent(object sender, ElapsedEventArgs e)
{
if (isMuted)
{
isMuted = false;
MuteSelectedItems(false);
// hide visual alert
InvalidateRect(IntPtr.Zero, activeRectangle, true);
notifyIcon1.Icon = Properties.Resources.MicOn;
if (InvokeRequired)
Invoke(new MethodInvoker(delegate { Icon = Properties.Resources.MicOn; }));
else
Icon = Properties.Resources.MicOn;
if (reloadDevicesOnNextUnmute)
{
reloadDevicesOnNextUnmute = false;
ReloadDevices();
}
}
}
private void OnRefreshDevicesTimedEvent(object sender, ElapsedEventArgs e)
{
ReloadDevices();
}
private void MuteSelectedItems(bool mute = true)
{
foreach (var name in GetSelectedItemNames())
{
MuteInput(name, mute);
}
}
private IEnumerable<string> GetSelectedItemNames()
{
var names = new List<string>();
foreach (DataGridViewRow row in dgvInputs.Rows)
{
var selected = (bool)row.Cells[(int)DeviceGridColumns.Selected].Value;
if (selected)
{
var name = row.Cells[(int)DeviceGridColumns.Name].Value.ToString();
names.Add(name);
}
}
return names;
}
private bool IsInUseByApplication()
{
foreach (DataGridViewRow row in dgvInputs.Rows)
{
var selected = (bool)row.Cells[(int)DeviceGridColumns.Selected].Value;
if (selected)
{
var name = row.Cells[(int)DeviceGridColumns.Name].Value.ToString();
if (inputs.IsActiveInApplication(name, new string[] { "Teams", "Zoom" }))
return true;
}
}
return false;
}
private void MuteAllInputs(bool mute = true)
{
if (!IsInUseByApplication())
return;
foreach (DataGridViewRow row in dgvInputs.Rows)
{
var name = row.Cells[(int)DeviceGridColumns.Name].Value.ToString();
MuteInput(name, mute);
}
}
private void MuteInput(string name, bool mute = true)
{
try
{
inputs.MuteInputByName(name, mute);
var row = GetRowByName(name);
row.Cells[(int)DeviceGridColumns.Muted].Value = mute;
row.Cells[(int)DeviceGridColumns.Name].Style.BackColor = mute ? Color.LightPink : defaultCellBgColor;
}
catch (COMException)
{
reloadDevicesOnNextUnmute = true;
inputs.RemoveActiveInput(name);
}
}
private void btnUnmuteAll_Click(object sender, EventArgs e)
{
MuteAllInputs(false);
}
// Ref: https://stackoverflow.com/questions/34090190/c-sharp-datagridview-checkbox-checked-event
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
// ignore header
if (e.RowIndex == -1)
return;
// ignore name cell
if (e.ColumnIndex != (int)DeviceGridColumns.Selected && e.ColumnIndex != (int)DeviceGridColumns.Muted)
return;
dgvInputs.CommitEdit(DataGridViewDataErrorContexts.Commit);
var name = dgvInputs.Rows[e.RowIndex].Cells[(int)DeviceGridColumns.Name].Value.ToString();
var isChecked = (bool)dgvInputs.CurrentCell.Value == true;
if (e.ColumnIndex == (int)DeviceGridColumns.Selected)
{
if (isChecked)
config.DevicesToMute.Add(name);
else
config.DevicesToMute.Remove(name);
config.Save();
}
else if (e.ColumnIndex == (int)DeviceGridColumns.Muted)
{
MuteInput(name, isChecked);
}
}
private DataGridViewRow GetRowByName(string name)
{
foreach (DataGridViewRow row in dgvInputs.Rows)
if (row.Cells[(int)DeviceGridColumns.Name].Value.ToString() == name)
return row;
return null;
}
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
dgvInputs.ClearSelection();
}
private void btnReload_Click(object sender, EventArgs e)
{
ReloadDevices();
}
private void ReloadDevices()
{
inputs = new InputDevices();
dgvInputs.Rows.Clear();
PopulateGrid();
}
private void trackBar1_Scroll(object sender, EventArgs e)
{
config.Save();
}
private void trackBar1_ValueChanged(object sender, EventArgs e)
{
int intervalms = (sender as TrackBar).Value;
SetNewInterval(intervalms);
config.MuteIntervalMs = intervalms;
config.Save();
}
private void SetNewInterval(int intervalMilliseconds)
{
lblUnmuteDuration.Text = $"Unmute after {intervalMilliseconds} ms";
unmuteTimer.Interval = intervalMilliseconds;
}
private enum DeviceGridColumns
{
Selected, Name, Muted
}
private void btnReloadDevices_Click(object sender, EventArgs e)
{
ReloadDevices();
}
private void Form1_Resize(object sender, EventArgs e)
{
notifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
if (FormWindowState.Minimized == WindowState)
{
notifyIcon1.Visible = true;
FormBorderStyle = FormBorderStyle.FixedToolWindow;
//notifyIcon1.ShowBalloonTip(500);
ShowInTaskbar = false;
}
else if (FormWindowState.Normal == WindowState)
{
notifyIcon1.Visible = false;
FormBorderStyle = FormBorderStyle.FixedSingle;
}
}
private void chkIgnoreAltTab_Click(object sender, EventArgs e)
{
config.IgnoreModifierKeys = (sender as CheckBox).Checked;
config.Save();
}
private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
{
WindowState = FormWindowState.Normal;
notifyIcon1.Visible = false;
ShowInTaskbar = true;
}
// screen lock event handler
private void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
{
if (e.Reason == SessionSwitchReason.SessionUnlock)
{
ReloadDevices();
}
}
[DllImport("user32.dll")]
static extern bool InvalidateRect(IntPtr hWnd, RECT lpRect, bool bErase);
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int Left, Top, Right, Bottom;
public RECT(int left, int top, int right, int bottom)
{
Left = left;
Top = top;
Right = right;
Bottom = bottom;
}
public RECT(Rectangle r) : this(r.Left, r.Top, r.Right, r.Bottom) { }
public int X
{
get { return Left; }
set { Right -= (Left - value); Left = value; }
}
public int Y
{
get { return Top; }
set { Bottom -= (Top - value); Top = value; }
}
public int Height
{
get { return Bottom - Top; }
set { Bottom = value + Top; }
}
public int Width
{
get { return Right - Left; }
set { Right = value + Left; }
}
public Point Location
{
get { return new Point(Left, Top); }
set { X = value.X; Y = value.Y; }
}
public Size Size
{
get { return new Size(Width, Height); }
set { Width = value.Width; Height = value.Height; }
}
public static implicit operator Rectangle(RECT r)
{
return new Rectangle(r.Left, r.Top, r.Width, r.Height);
}
public static implicit operator RECT(Rectangle r)
{
return new RECT(r);
}
public static bool operator ==(RECT r1, RECT r2)
{
return r1.Equals(r2);
}
public static bool operator !=(RECT r1, RECT r2)
{
return !r1.Equals(r2);
}
public bool Equals(RECT r)
{
return r.Left == Left && r.Top == Top && r.Right == Right && r.Bottom == Bottom;
}
public override bool Equals(object obj)
{
if (obj is RECT)
return Equals((RECT)obj);
else if (obj is Rectangle)
return Equals(new RECT((Rectangle)obj));
return false;
}
public override int GetHashCode()
{
return ((Rectangle)this).GetHashCode();
}
public override string ToString()
{
return string.Format(System.Globalization.CultureInfo.CurrentCulture, "{{Left={0},Top={1},Right={2},Bottom={3}}}", Left, Top, Right, Bottom);
}
}
private void chkStartMinimized_CheckedChanged(object sender, EventArgs e)
{
var chk = sender as CheckBox;
config.StartMinimized = chk.Checked;
config.Save();
}
}
}