-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMainWindow.xaml.cs
1553 lines (1312 loc) · 57.3 KB
/
MainWindow.xaml.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
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 SharpDX.XInput;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows;
using System.Linq;
using System.Windows.Media;
using System.Globalization;
using System.Windows.Data;
using System.Drawing;
using System.Windows.Forms;
using System.ComponentModel;
using System.Threading.Tasks;
using System.IO;
using Size = System.Drawing.Size;
using Point = System.Drawing.Point;
using System.Windows.Threading;
using System.Windows.Input;
using System.Threading;
using System.Windows.Media.Imaging;
using System.Windows.Media.Animation;
using NAudio.CoreAudioApi;
using System.Data;
using Windows.Devices.Sms;
using System.Windows.Controls;
using Application = System.Windows.Application;
using NAudio.Wave;
using AudioSwitcher.AudioApi.CoreAudio;
using System.Text;
using MessageBox = System.Windows.MessageBox;
using KeyEventArgs = System.Windows.Input.KeyEventArgs;
using Button = System.Windows.Controls.Button;
using System.Windows.Controls.Primitives;
using Windows.UI.Xaml.Controls;
using Grid = System.Windows.Controls.Grid;
using ComboBox = System.Windows.Forms.ComboBox;
using System.Windows.Media.Effects;
using MaterialDesignColors;
using MaterialDesignThemes.Wpf;
using System.Windows.Interop;
using System.Reflection;
using Border = System.Windows.Controls.Border;
using Color = System.Windows.Media.Color;
using NAudio.Utils;
namespace WindowSelector
{
public class WindowItem
{
public string Name { get; set; }
public Process Process { get; set; }
public IntPtr WindowHandle { get; set; }
public BitmapImage Preview { get; set; } // Store the preview image
}
public class WindowSinker
{
#region Properties
private const UInt32 SWP_NOSIZE = 0x0001;
private const UInt32 SWP_NOMOVE = 0x0002;
private const UInt32 SWP_NOACTIVATE = 0x0010;
private const UInt32 SWP_NOZORDER = 0x0004;
private const int WM_ACTIVATEAPP = 0x001C;
private const int WM_ACTIVATE = 0x0006;
private const int WM_SETFOCUS = 0x0007;
private const int WM_WINDOWPOSCHANGING = 0x0046;
private static readonly IntPtr HWND_TOPMOST = new IntPtr(1);
private Window Window = null;
#endregion Properties
#region WindowSinker
public WindowSinker(Window Window)
{
this.Window = Window;
}
#endregion WindowSinker
#region Methods
[DllImport("user32.dll")]
private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
[DllImport("user32.dll")]
private static extern IntPtr DeferWindowPos(IntPtr hWinPosInfo, IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, uint uFlags);
[DllImport("user32.dll")]
private static extern IntPtr BeginDeferWindowPos(int nNumWindows);
[DllImport("user32.dll")]
private static extern bool EndDeferWindowPos(IntPtr hWinPosInfo);
private void OnClosing(object sender, System.ComponentModel.CancelEventArgs e)
{
var Handle = (new WindowInteropHelper(Window)).Handle;
var Source = HwndSource.FromHwnd(Handle);
Source.RemoveHook(new HwndSourceHook(WndProc));
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
var Hwnd = new WindowInteropHelper(Window).Handle;
SetWindowPos(Hwnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE);
var Handle = (new WindowInteropHelper(Window)).Handle;
var Source = HwndSource.FromHwnd(Handle);
Source.AddHook(new HwndSourceHook(WndProc));
}
private IntPtr WndProc(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
if (msg == WM_SETFOCUS)
{
hWnd = new WindowInteropHelper(Window).Handle;
SetWindowPos(hWnd, (IntPtr)(-1), 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
handled = true;
}
return IntPtr.Zero;
}
public void Sink()
{
Window.Loaded += OnLoaded;
Window.Closing += OnClosing;
}
public void Unsink()
{
Window.Loaded -= OnLoaded;
Window.Closing -= OnClosing;
}
#endregion Methods
}
public static class WindowExtensions
{
#region Always On Bottom
public static readonly DependencyProperty SinkerProperty = DependencyProperty.RegisterAttached("Sinker", typeof(WindowSinker), typeof(WindowExtensions), new UIPropertyMetadata(null));
public static WindowSinker GetSinker(DependencyObject obj)
{
return (WindowSinker)obj.GetValue(SinkerProperty);
}
public static void SetSinker(DependencyObject obj, WindowSinker value)
{
obj.SetValue(SinkerProperty, value);
}
public static readonly DependencyProperty AlwaysOnBottomProperty = DependencyProperty.RegisterAttached("AlwaysOnBottom", typeof(bool), typeof(WindowExtensions), new UIPropertyMetadata(false, OnAlwaysOnBottomChanged));
public static bool GetAlwaysOnBottom(DependencyObject obj)
{
return (bool)obj.GetValue(AlwaysOnBottomProperty);
}
public static void SetAlwaysOnBottom(DependencyObject obj, bool value)
{
obj.SetValue(AlwaysOnBottomProperty, value);
}
private static void OnAlwaysOnBottomChanged(object sender, DependencyPropertyChangedEventArgs e)
{
var Window = sender as Window;
if (Window != null)
{
if ((bool)e.NewValue)
{
var Sinker = new WindowSinker(Window);
Sinker.Sink();
SetSinker(Window, Sinker);
}
else
{
var Sinker = GetSinker(Window);
Sinker.Unsink();
SetSinker(Window, null);
}
}
}
#endregion Always On Bottom
}
public class LazyImageLoader : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is IntPtr hwnd && hwnd != IntPtr.Zero)
{
Bitmap resizedBmp = null;
try
{
Bitmap bmp = MainWindow.PrintWindow(hwnd); // Capture the window image
double scaleFactor = 1.5;
// Calculate the maximum width based on the screen width and scale factor
int maxWidth = (int)(System.Windows.SystemParameters.PrimaryScreenWidth * scaleFactor);
int maxHeight = (int)(System.Windows.SystemParameters.PrimaryScreenHeight * scaleFactor);
double ratioX = (double)maxWidth / bmp.Width;
double ratioY = (double)maxHeight / bmp.Height;
double ratio = Math.Min(ratioX, ratioY);
int newWidth = (int)(bmp.Width * ratio);
int newHeight = (int)(bmp.Height * ratio);
resizedBmp = new Bitmap(bmp, newWidth, newHeight); // Use the resized bitmap
using (MemoryStream memory = new MemoryStream())
{
resizedBmp.Save(memory, System.Drawing.Imaging.ImageFormat.Jpeg); // Save as JPEG
memory.Position = 0;
BitmapImage bitmapimage = new BitmapImage();
bitmapimage.BeginInit();
bitmapimage.StreamSource = memory;
bitmapimage.CacheOption = BitmapCacheOption.OnLoad;
bitmapimage.EndInit();
bitmapimage.Freeze(); // Important for use in another thread
return bitmapimage;
}
}
catch
{
// Handle exceptions or return a default image
return DependencyProperty.UnsetValue;
}
finally
{
resizedBmp?.Dispose(); // Ensure resizedBmp is disposed of correctly
}
}
return DependencyProperty.UnsetValue; // Return an unset value if conversion is not possible
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
public class AudioDevice
{
public string Name { get; set; }
public Guid Id { get; set; }
public bool IsInput { get; set; } // True for input devices, false for output
}
// Convert window titles to uppercase function
public class StringToUpperConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value.ToString().ToUpper();
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
public class SimplifyDeviceNameConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var fullName = value as string;
if (string.IsNullOrEmpty(fullName)) return "";
// Example logic to trim after the first occurrence of '('
var simplifiedName = fullName.Split('(')[0].Trim();
return simplifiedName;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
public class CompositeConverter : IValueConverter
{
public IValueConverter First { get; set; }
public IValueConverter Second { get; set; }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var firstResult = First.Convert(value, targetType, parameter, culture);
return Second.Convert(firstResult, targetType, parameter, culture);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
public partial class MainWindow : Window
{
private readonly Controller controller;
private const int ASFW_ANY = -1;
private NotifyIcon trayIcon;
private GamepadButtonFlags previousButtons = GamepadButtonFlags.None;
private DispatcherTimer gamepadTimer;
private Gamepad previousGamepadState;
private bool aButtonPressed = false;
private WindowSinker sinker;
private DispatcherTimer topmostCheckTimer;
public MainWindow()
{
sinker = new WindowSinker(this);
sinker.Sink();
InitializeComponent();
InitializeMaterialDesign();
InitializeGamepadPolling();
_ = PopulateAudioDevicesAsync();
AllowSetForegroundWindow(ASFW_ANY); // Allow any process to bring this window to foreground
if (this.WindowState == WindowState.Minimized)
{
this.WindowState = WindowState.Normal;
}
this.Activate();
BringApplicationToFront();
refreshTimer = new DispatcherTimer();
refreshTimer.Interval = TimeSpan.FromSeconds(1); // Adjust the interval as needed
refreshTimer.Tick += (sender, e) => RefreshWindowTitlesIfNeeded();
refreshTimer.Start();
// Initialize knownWindowHandles to force the first refresh
var initialWindows = GetOpenWindows();
knownWindowHandles = new HashSet<IntPtr>(initialWindows.Select(w => w.MainWindowHandle));
// Explicitly populate the window list at startup with the current windows
RefreshWindowTitles(initialWindows); // Now correctly passing the initialWindows as the argument
this.WindowState = WindowState.Maximized;
this.Width = SystemParameters.PrimaryScreenWidth;
this.Height = SystemParameters.PrimaryScreenHeight;
this.ShowInTaskbar = false;
trayIcon = new NotifyIcon();
trayIcon.Icon = new System.Drawing.Icon("OS.ico");
trayIcon.Visible = false;
// Add the application icon to the system tray
this.Loaded += MainWindow_Loaded;
// Ensure the tray icon is removed when the application exits
Application.Current.Exit += Current_Exit;
System.Windows.Forms.ContextMenu trayMenu = new System.Windows.Forms.ContextMenu();
System.Windows.Forms.MenuItem quitItem = new System.Windows.Forms.MenuItem("Quit");
quitItem.Click += (sender, e) => System.Windows.Application.Current.Shutdown();
trayMenu.MenuItems.Add(quitItem);
trayIcon.ContextMenu = trayMenu;
controller = new Controller(UserIndex.One);
this.MouseDown += new MouseButtonEventHandler(MainWindow_MouseDown);
}
private DispatcherTimer refreshTimer;
// Define the constants
private const UInt32 SWP_NOSIZE = 0x0001;
private const UInt32 SWP_NOMOVE = 0x0002;
// Declare the external method
[DllImport("user32.dll")]
private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
private void OnLoaded(object sender, RoutedEventArgs e)
{
var Hwnd = new WindowInteropHelper(this).Handle; // Use 'this' to refer to the current window instance
SetWindowPos(Hwnd, (IntPtr)(-1), 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
}
private void BringApplicationToFront()
{
var windowHandle = new WindowInteropHelper(this).Handle;
SetForegroundWindow(windowHandle);
BringWindowToTop(windowHandle);
}
private DispatcherTimer focusCheckTimer;
private void SetupFocusCheckTimer()
{
focusCheckTimer = new DispatcherTimer();
focusCheckTimer.Interval = TimeSpan.FromMilliseconds(500); // Check every 500 milliseconds
focusCheckTimer.Tick += FocusCheckTimer_Tick;
focusCheckTimer.Start();
}
private void FocusCheckTimer_Tick(object sender, EventArgs e)
{
IntPtr foregroundWindow = GetForegroundWindow();
IntPtr myWindowHandle = new WindowInteropHelper(this).Handle;
if (foregroundWindow != myWindowHandle)
{
// Your window is not at the front
MinimizeBlockingWindow(foregroundWindow);
}
}
private void MinimizeBlockingWindow(IntPtr windowHandle)
{
// Minimize the window that's currently blocking ours
ShowWindow(windowHandle, SW_MINIMIZE);
}
private void EnsureAlwaysOnTop()
{
// Temporarily disable TopMost to trigger internal window state update
this.Topmost = false;
this.Activate();
this.Topmost = true;
// Attempt to bring window to the foreground
var hwnd = new WindowInteropHelper(this).Handle;
SetForegroundWindow(hwnd);
}
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
MakeWindowAlwaysOnTop(); // Ensure window is always on top when loaded
SetupWindowMessageHook(); // Start monitoring window messages
// Existing logic...
if (!trayIcon.Visible)
{
trayIcon.Visible = true;
HideAudioDevicesPopup();
this.Hide(); // Hide main window initially, if that's the intended behavior
}
}
private void Current_Exit(object sender, ExitEventArgs e)
{
if (trayIcon != null)
{
trayIcon.Visible = false;
trayIcon.Dispose();
}
}
private void InitializeGamepadPolling()
{
gamepadTimer = new DispatcherTimer
{
Interval = TimeSpan.FromMilliseconds(10) // Needs more adjustments
};
gamepadTimer.Tick += GamepadPollingTick;
gamepadTimer.Start();
}
private bool previousDpadUpPressed = false;
private bool previousDpadDownPressed = false;
private void GamepadPollingTick(object sender, EventArgs e)
{
if (!controller.IsConnected) return;
var gamepadState = controller.GetState().Gamepad;
bool l1Pressed = gamepadState.Buttons.HasFlag(GamepadButtonFlags.LeftShoulder);
bool r1Pressed = gamepadState.Buttons.HasFlag(GamepadButtonFlags.RightShoulder);
bool dpadLeftPressed = gamepadState.Buttons.HasFlag(GamepadButtonFlags.DPadLeft);
bool dpadRightPressed = gamepadState.Buttons.HasFlag(GamepadButtonFlags.DPadRight);
bool yPressed = gamepadState.Buttons.HasFlag(GamepadButtonFlags.Y);
bool xPressed = gamepadState.Buttons.HasFlag(GamepadButtonFlags.X);
bool windowListboxUp = gamepadState.Buttons.HasFlag(GamepadButtonFlags.DPadUp);
bool windowListboxDown = gamepadState.Buttons.HasFlag(GamepadButtonFlags.DPadDown);
// Check if the current application is the active window
IntPtr foregroundWindow = GetForegroundWindow();
GetWindowThreadProcessId(foregroundWindow, out int foregroundProcId);
Process foregroundProc = Process.GetProcessById(foregroundProcId);
if (this.WindowState == WindowState.Minimized || !this.IsVisible)
{
// Restore window from tray if L1, R1, and DPad Left are pressed
if (l1Pressed && r1Pressed && dpadLeftPressed)
{
Dispatcher.Invoke(() =>
{
RestoreWindowFromTray();
});
}
// Ignore further gamepad inputs since the window is minimized or not visible
return;
}
// Check if the application is minimized
if (this.WindowState == WindowState.Minimized)
{
// Restore window from tray if L1, R1, and DPad Left are pressed
if (gamepadState.Buttons.HasFlag(GamepadButtonFlags.LeftShoulder) &&
gamepadState.Buttons.HasFlag(GamepadButtonFlags.RightShoulder) &&
gamepadState.Buttons.HasFlag(GamepadButtonFlags.DPadLeft))
{
Dispatcher.Invoke(() =>
{
RestoreWindowFromTray();
});
}
else
{
return; // Ignore other inputs if the application is minimized
}
}
else if (AudioDevicesPopup.IsOpen)
{
// Prevent double dpad input when activating the popup
if ((DateTime.Now - lastMenuOpenTime).TotalMilliseconds < 150)
{
// Not enough time has passed, ignore the input
return;
}
// Directly select output or input tab using DPad left and right
if (dpadLeftPressed)
{
AudioDeviceTabs.SelectedIndex = 0; // Output tab selected
}
else if (dpadRightPressed)
{
AudioDeviceTabs.SelectedIndex = 1; // Input tab selected
}
else
{
// Handle input specifically for the selected device list (input or output)
var selectedTab = AudioDeviceTabs.SelectedItem as TabItem;
var AudioDeviceListBox = selectedTab.Content as System.Windows.Controls.ListBox;
// Ensure we only move the selection if the DPad was not previously pressed
if (windowListboxUp && !previousGamepadState.Buttons.HasFlag(GamepadButtonFlags.DPadUp))
{
// Prevent index from going below 0
if (AudioDeviceListBox.SelectedIndex > 0)
{
AudioDeviceListBox.SelectedIndex--;
}
}
else if (windowListboxDown && !previousGamepadState.Buttons.HasFlag(GamepadButtonFlags.DPadDown))
{
// Prevent index from exceeding the count of items
if (AudioDeviceListBox.SelectedIndex < AudioDeviceListBox.Items.Count - 1)
{
AudioDeviceListBox.SelectedIndex++;
}
}
// confirm audio device selection
if (gamepadState.Buttons.HasFlag(GamepadButtonFlags.A) && !previousGamepadState.Buttons.HasFlag(GamepadButtonFlags.A))
{
var selectedDevice = AudioDeviceListBox.SelectedItem as AudioDevice;
if (selectedDevice != null)
{
ChangeAudioDeviceToSelected(selectedDevice);
aButtonPressed = false;
}
}
// close audio devices popup
if (gamepadState.Buttons.HasFlag(GamepadButtonFlags.B) && !previousGamepadState.Buttons.HasFlag(GamepadButtonFlags.B))
{
HideAudioDevicesPopup();
}
}
// Save the current gamepad state for the next tick
previousGamepadState = gamepadState;
}
else
{
// If the audio menu is not visible and the 'B' button is pressed, hide the main window to the tray.
if (gamepadState.Buttons.HasFlag(GamepadButtonFlags.B) && !previousGamepadState.Buttons.HasFlag(GamepadButtonFlags.B))
{
Dispatcher.Invoke(() =>
{
this.Hide(); // Hide the main window
trayIcon.Visible = true; // Make sure the tray icon is visible
HideAudioDevicesPopup();
});
}
if (gamepadState.Buttons.HasFlag(GamepadButtonFlags.A) && !previousGamepadState.Buttons.HasFlag(GamepadButtonFlags.A))
{
aButtonPressed = true;
// Minimize the selected window first
if (WindowListBox.SelectedItem != null)
{
dynamic selectedItem = WindowListBox.SelectedItem;
var process = selectedItem.Process as Process;
if (process != null && process.MainWindowHandle != IntPtr.Zero)
{
// Assuming ShowWindow and SW_MINIMIZE are already defined appropriately
ShowWindow(process.MainWindowHandle, SW_MINIMIZE);
}
}
// Now proceed to hide the main window and show the tray icon
WindowListBox_SelectionChanged(WindowListBox, null); // Assuming this is still required for your logic
this.Hide();
trayIcon.Visible = true;
HideAudioDevicesPopup();
aButtonPressed = false;
}
if (yPressed && !previousButtons.HasFlag(GamepadButtonFlags.Y))
{
// Minimize the selected window
if (WindowListBox.SelectedItem != null)
{
dynamic selectedItem = WindowListBox.SelectedItem;
var process = selectedItem.Process as Process;
if (process != null && process.MainWindowHandle != IntPtr.Zero)
{
ShowWindow(process.MainWindowHandle, SW_MINIMIZE);
this.Activate();
this.Focus();
SetForegroundWindow(new WindowInteropHelper(this).Handle);
}
}
}
if (xPressed && !previousButtons.HasFlag(GamepadButtonFlags.X))
{
// More gracefully close the selected window
if (WindowListBox.SelectedItem != null)
{
dynamic selectedItem = WindowListBox.SelectedItem;
var process = selectedItem.Process as Process;
if (process != null)
{
if (process.MainWindowHandle != IntPtr.Zero)
{
PostMessage(process.MainWindowHandle, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
}
else
{
try
{
process.Kill();
}
catch (Exception ex)
{
// Handle the exception, log, etc
}
}
}
}
}
// DPad Up navigation logic
if (windowListboxUp)
{
if (!previousDpadUpPressed)
{
if (WindowListBox.SelectedIndex > 0)
{
WindowListBox.SelectedIndex--;
}
previousDpadUpPressed = true;
}
}
else
{
previousDpadUpPressed = false;
}
// DPad Down navigation logic
if (windowListboxDown)
{
if (!previousDpadDownPressed)
{
if (WindowListBox.SelectedIndex < WindowListBox.Items.Count - 1)
{
WindowListBox.SelectedIndex++;
}
previousDpadDownPressed = true;
}
}
else
{
previousDpadDownPressed = false;
}
if (dpadRightPressed && !previousButtons.HasFlag(GamepadButtonFlags.DPadRight))
{
// show list of audio devices
ShowAudioDevicesPopup();
lastMenuOpenTime = DateTime.Now;
}
if (gamepadState.Buttons.HasFlag(GamepadButtonFlags.B) && !previousButtons.HasFlag(GamepadButtonFlags.B))
{
if (!isAudioDeviceListVisible)
{
Dispatcher.Invoke(() =>
{
// hide the audio devices popup
AudioDevicesPopup.IsOpen = false;
});
}
else
{
this.Hide();
trayIcon.Visible = true;
HideAudioDevicesPopup();
}
}
}
if (gamepadState.Buttons.HasFlag(GamepadButtonFlags.B) && !previousGamepadState.Buttons.HasFlag(GamepadButtonFlags.B))
{ // if the tray icon is not visible and the 'B' button is pressed, hide the main window to the tray
if (!trayIcon.Visible)
{
Dispatcher.Invoke(() =>
{
this.Hide(); // Hide the main window
trayIcon.Visible = true; // Make sure the tray icon is visible
HideAudioDevicesPopup();
});
}
}
previousGamepadState = gamepadState;
}
private DateTime lastMenuOpenTime = DateTime.MinValue;
private void ShowAudioDevicesPopup()
{
// Ensure the popup is closed before adjusting its position, to avoid visual glitches.
AudioDevicesPopup.IsOpen = false;
// Calculate the desired position for the popup.
var windowLocation = this.PointToScreen(new System.Windows.Point(0, 0));
var windowHeight = this.ActualHeight;
var windowWidth = this.ActualWidth;
var popupHeight = PopupContent.ActualHeight;
var popupWidth = PopupContent.ActualWidth;
// Set the position to the bottom right of the window.
AudioDevicesPopup.HorizontalOffset = windowLocation.X + windowWidth - popupWidth - 20;
AudioDevicesPopup.VerticalOffset = windowLocation.Y + windowHeight - popupHeight - 20;
// Now open the popup.
AudioDevicesPopup.IsOpen = true;
// Start the animation, if any.
var popInStoryboard = FindResource("OpenAudioDevicePopupAnimation") as Storyboard;
if (popInStoryboard != null)
{
Storyboard.SetTarget(popInStoryboard, PopupContent);
popInStoryboard.Begin();
}
ApplyBlurEffectToMainWindowContent(true);
}
private void HideAudioDevicesPopup()
{
var popOutStoryboard = FindResource("CloseAudioDevicePopupAnimation") as Storyboard;
if (popOutStoryboard != null)
{
popOutStoryboard.Completed += (s, e) =>
{
AudioDevicesPopup.IsOpen = false;
};
Storyboard.SetTarget(popOutStoryboard, PopupContent);
popOutStoryboard.Begin();
ApplyBlurEffectToMainWindowContent(false);
}
else
{
AudioDevicesPopup.IsOpen = false;
}
}
private void ApplyBlurEffectToMainWindowContent(bool apply)
{
if (apply)
{
var blur = new BlurEffect();
RootPanel.Effect = blur;
var animation = new DoubleAnimation
{
From = 0,
To = 25, // Target blur radius
Duration = TimeSpan.FromSeconds(0.5),
FillBehavior = FillBehavior.Stop // Stops the animation at its final value
};
animation.Completed += (s, e) => blur.Radius = 25;
blur.BeginAnimation(BlurEffect.RadiusProperty, animation);
}
else
{
if (RootPanel.Effect is BlurEffect blur)
{
var animation = new DoubleAnimation
{
To = 0, // Animate back to no blur
Duration = TimeSpan.FromSeconds(0.5),
};
animation.Completed += (s, e) => RootPanel.Effect = null;
blur.BeginAnimation(BlurEffect.RadiusProperty, animation);
}
}
}
private void InitializeMaterialDesign()
{
// Create dummy objects to force the MaterialDesign assemblies to be loaded
// from this assembly, which causes the MaterialDesign assemblies to be searched
// relative to this assembly's path. Otherwise, the MaterialDesign assemblies
// are searched relative to Eclipse's path, so they're not found.
var card = new Card();
var hue = new Hue("Dummy", Colors.Black, Colors.White);
}
private CustomPopupPlacement[] PopupCustomPlacementMethod(Size popupSize, Size targetSize, Point offset)
{
var screen = System.Windows.SystemParameters.WorkArea;
var rightEdge = screen.Right;
var popupX = rightEdge - popupSize.Width;
var popupY = (screen.Height / 2) - (popupSize.Height / 2); // Center vertically
return new CustomPopupPlacement[] { new CustomPopupPlacement(new System.Windows.Point(popupX, popupY), PopupPrimaryAxis.None) };
}
private async Task PopulateAudioDevicesAsync()
{
LoadingTextBlock.Visibility = Visibility.Visible;
// Separate lists for input and output devices
var outputDeviceList = new List<AudioDevice>();
var inputDeviceList = new List<AudioDevice>();
await Task.Run(() =>
{
var controller = new CoreAudioController();
// Fetch output devices
outputDeviceList = controller.GetPlaybackDevices(AudioSwitcher.AudioApi.DeviceState.Active)
.Select(d => new AudioDevice { Name = d.FullName, Id = d.Id, IsInput = false }).ToList();
// Fetch input devices
inputDeviceList = controller.GetCaptureDevices(AudioSwitcher.AudioApi.DeviceState.Active)
.Select(d => new AudioDevice { Name = d.FullName, Id = d.Id, IsInput = true }).ToList();
});
Dispatcher.Invoke(() =>
{
AudioOutputDeviceList.ItemsSource = outputDeviceList;
AudioInputDeviceList.ItemsSource = inputDeviceList;
shouldUpdateDevices = false; // Reset the flag
LoadingTextBlock.Visibility = Visibility.Collapsed;
AudioOutputDeviceList.Visibility = Visibility.Visible; // Make the list visible
});
}
private async Task SetDefaultAudioDeviceAsync(Guid deviceId)
{
try
{
var controller = new AudioSwitcher.AudioApi.CoreAudio.CoreAudioController();
var device = await controller.GetDeviceAsync(deviceId).ConfigureAwait(false);
if (device != null)
{
await device.SetAsDefaultAsync().ConfigureAwait(false);
}
}
catch (Exception ex)
{
// Since this runs in a background thread, use Dispatcher.Invoke to show the message box
Dispatcher.Invoke(() =>
MessageBox.Show($"Error setting default audio device: {ex.Message}", "Error", MessageBoxButton.OK, MessageBoxImage.Error)
);
}
}
private DateTime lastRefreshTime = DateTime.MinValue;
private void MainWindow_MouseDown(object sender, MouseButtonEventArgs e)
{
// Check if the left mouse button was clicked
if (e.ButtonState == MouseButtonState.Pressed && e.ChangedButton == MouseButton.Left)
{
aButtonPressed = true;
WindowListBox_SelectionChanged(WindowListBox, null);
this.Hide();
trayIcon.Visible = true;
}
}
private void Window_Activated(object sender, EventArgs e)
{
this.Background = new SolidColorBrush(System.Windows.Media.Color.FromArgb(200, 0, 0, 0));
}
private bool isAudioDeviceListVisible = false;
private HashSet<IntPtr> knownWindowHandles = new HashSet<IntPtr>();
private void RefreshWindowTitlesIfNeeded()
{
var currentWindows = GetOpenWindows();
var currentHandles = new HashSet<IntPtr>(currentWindows.Select(w => w.MainWindowHandle));
// Check if the set of window handles has changed since the last check
if (!currentHandles.SetEquals(knownWindowHandles))
{
RefreshWindowTitles(currentWindows); // Pass the current windows to avoid fetching them again
knownWindowHandles = currentHandles; // Update the known handles
}
}
private void RefreshWindowTitles(IEnumerable<Process> currentWindows)
{
int selectedIndex = WindowListBox.SelectedIndex;
WindowListBox.ItemsSource = currentWindows.Select(p =>
{
var item = new WindowItem
{
Name = GetFriendlyName(p.ProcessName).ToUpper(),
Process = p,
WindowHandle = p.MainWindowHandle // Store the handle directly
};
return item;
}).ToList();
WindowListBox.SelectedIndex = Math.Min(selectedIndex, WindowListBox.Items.Count - 1);
}
private DateTime lastNavigationTime = DateTime.MinValue;
private List<CoreAudioDevice> audioDeviceCache = null;
private bool shouldUpdateDevices = true;
public List<MMDevice> GetAudioOutputDevices()
{
var enumerator = new MMDeviceEnumerator();
var devices = enumerator.EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active).ToList();
return devices;
}
private async void ChangeAudioDeviceToSelected(AudioDevice selectedDevice)
{
if (selectedDevice == null) return;
try
{
// Reset UI to initial state explicitly
Dispatcher.Invoke(() =>
{
// Ensure LoadingText is visible
LoadingText.Visibility = Visibility.Visible;
// Reset backgrounds to transparent
LoadingTextBackground.Background = new SolidColorBrush(Colors.Transparent);
CompletedTextBackground.Background = new SolidColorBrush(Colors.Transparent);
});
// Simulate the operation
await Task.Run(() => SetDefaultAudioDeviceAsync(selectedDevice.Id));
// Immediately after operation, prepare for showing CompletedText
Dispatcher.Invoke(() =>
{
// Hide LoadingText
LoadingText.Visibility = Visibility.Collapsed;
// Set background to green for visibility and make CompletedText visible and fully opaque
CompletedTextBackground.Background = new SolidColorBrush(Colors.Green);
CompletedText.Visibility = Visibility.Visible;
CompletedText.Opacity = 1;
});
// Immediately fade out after ensuring CompletedText is visible
var fadeOutAnimation = new DoubleAnimation