-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
266 lines (227 loc) · 9.84 KB
/
MainWindow.xaml.cs
File metadata and controls
266 lines (227 loc) · 9.84 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
// This is the "code-behind" file for your main window.
// It handles button clicks, populates the list, and calls the DisplayManager.
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using System;
using System.IO;
using System.Linq;
using Microsoft.UI.Windowing; // Required for AppWindow
using System.Runtime.InteropServices; // Required for P/Invoke (API calls)
using WinRT.Interop; // Required for window handle interop
namespace MonPro
{
public sealed partial class MainWindow : Window
{
// We will store profile .json files in a dedicated folder in the user's AppData directory.
private readonly string _profilesPath;
// New members for tray icon functionality
private AppWindow _appWindow;
private bool _isExiting = false;
private IntPtr _hWnd = IntPtr.Zero;
private delegate int SUBCLASSPROC(IntPtr hWnd, uint uMsg, IntPtr wParam, IntPtr lParam, IntPtr uIdSubclass, IntPtr dwRefData);
private readonly SUBCLASSPROC _wndProcDelegate;
public MainWindow()
{
this.InitializeComponent();
this.Title = "Monitor Profile Manager";
// --- New setup for tray icon and window handling ---
_hWnd = WindowNative.GetWindowHandle(this);
WindowId wndId = Microsoft.UI.Win32Interop.GetWindowIdFromWindow(_hWnd);
_appWindow = AppWindow.GetFromId(wndId);
// Intercept window messages for tray icon clicks
_wndProcDelegate = new SUBCLASSPROC(SubclassProc);
SetWindowSubclass(_hWnd, _wndProcDelegate, 0, 0);
// Subscribe to the closing event to override it
_appWindow.Closing += OnWindowClosing;
// --- End of new setup ---
// Define the path where profiles will be saved.
string appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
_profilesPath = Path.Combine(appDataPath, "MonPro", "Profiles");
// Ensure the directory exists.
Directory.CreateDirectory(_profilesPath);
// Load any existing profiles into the list when the app starts.
RefreshProfilesList();
}
#region Core App Logic
private void SaveProfileButton_Click(object sender, RoutedEventArgs e)
{
string profileName = ProfileNameTextBox.Text.Trim();
if (string.IsNullOrWhiteSpace(profileName)) return;
string safeFileName = string.Join("_", profileName.Split(Path.GetInvalidFileNameChars()));
string filePath = Path.Combine(_profilesPath, $"{safeFileName}.json");
DisplayManager.SaveCurrentProfile(filePath);
ProfileNameTextBox.Text = "";
RefreshProfilesList();
}
private void LoadProfileButton_Click(object sender, RoutedEventArgs e)
{
if (ProfileListView.SelectedItem is string profileName)
{
string filePath = Path.Combine(_profilesPath, $"{profileName}.json");
DisplayManager.LoadProfile(filePath);
}
}
private void DeleteProfileButton_Click(object sender, RoutedEventArgs e)
{
if (ProfileListView.SelectedItem is string profileName)
{
string filePath = Path.Combine(_profilesPath, $"{profileName}.json");
if (File.Exists(filePath))
{
File.Delete(filePath);
}
RefreshProfilesList();
}
}
private void RefreshProfilesList()
{
ProfileListView.Items.Clear();
var profileFiles = Directory.GetFiles(_profilesPath, "*.json");
foreach (var file in profileFiles)
{
ProfileListView.Items.Add(Path.GetFileNameWithoutExtension(file));
}
}
#endregion
#region Tray Icon and Window Management
/// <summary>
/// Overrides the standard window closing behavior.
/// </summary>
private void OnWindowClosing(AppWindow sender, AppWindowClosingEventArgs args)
{
if (!_isExiting)
{
// Prevent the window from closing
args.Cancel = true;
// Add the icon to the tray and hide the main window
AddTrayIcon();
_appWindow.Hide();
}
}
/// <summary>
/// A custom message processor to handle clicks on our tray icon.
/// </summary>
private int SubclassProc(IntPtr hWnd, uint uMsg, IntPtr wParam, IntPtr lParam, IntPtr uIdSubclass, IntPtr dwRefData)
{
// Check if the message is from our tray icon
if (uMsg == WM_TRAYICON)
{
// Check for mouse clicks
if (lParam.ToInt32() == WM_LBUTTONUP) // Left-click to restore
{
RestoreWindow();
}
else if (lParam.ToInt32() == WM_RBUTTONUP) // Right-click for context menu
{
ShowContextMenu();
}
}
// Pass messages on to the default processor
return DefSubclassProc(hWnd, uMsg, wParam, lParam);
}
private void ShowContextMenu()
{
// Create a native Win32 popup menu
IntPtr menu = CreatePopupMenu();
AppendMenu(menu, MF_STRING, 1001, "Show");
AppendMenu(menu, MF_STRING, 1002, "Exit");
// Set position and show the menu
GetCursorPos(out POINT pt);
SetForegroundWindow(_hWnd);
int command = TrackPopupMenu(menu, TPM_RETURNCMD, pt.x, pt.y, 0, _hWnd, IntPtr.Zero);
// Handle the user's choice
if (command == 1001) // Show
{
RestoreWindow();
}
else if (command == 1002) // Exit
{
ExitApplication();
}
DestroyMenu(menu);
}
private void RestoreWindow()
{
RemoveTrayIcon();
_appWindow.Show();
}
private void ExitApplication()
{
_isExiting = true;
RemoveTrayIcon();
Application.Current.Exit();
}
private void AddTrayIcon()
{
var notifyIconData = new NOTIFYICONDATA();
notifyIconData.cbSize = (uint)Marshal.SizeOf(notifyIconData);
notifyIconData.hWnd = _hWnd;
notifyIconData.uID = 1;
notifyIconData.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
notifyIconData.uCallbackMessage = WM_TRAYICON;
notifyIconData.szTip = "Monitor Profile Switcher";
// IMPORTANT: This assumes you have an "icon.ico" file in your project's Assets folder.
string iconPath = Path.Combine(AppContext.BaseDirectory, "Assets/icon.ico");
notifyIconData.hIcon = LoadImage(IntPtr.Zero, iconPath, 1, 0, 0, 0x0010);
Shell_NotifyIcon(NIM_ADD, ref notifyIconData);
}
private void RemoveTrayIcon()
{
var notifyIconData = new NOTIFYICONDATA();
notifyIconData.cbSize = (uint)Marshal.SizeOf(notifyIconData);
notifyIconData.hWnd = _hWnd;
notifyIconData.uID = 1;
Shell_NotifyIcon(NIM_DELETE, ref notifyIconData);
}
#endregion
#region P/Invoke Definitions for Win32 API
// Constants
private const int WM_TRAYICON = 0x800;
private const int WM_LBUTTONUP = 0x0202;
private const int WM_RBUTTONUP = 0x0205;
private const uint MF_STRING = 0x0000;
private const uint TPM_RETURNCMD = 0x0100;
private const uint NIM_ADD = 0x00;
private const uint NIM_DELETE = 0x02;
private const uint NIF_ICON = 0x02;
private const uint NIF_MESSAGE = 0x01;
private const uint NIF_TIP = 0x04;
// Structures
[StructLayout(LayoutKind.Sequential)]
private struct POINT { public int x; public int y; }
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct NOTIFYICONDATA
{
public uint cbSize;
public IntPtr hWnd;
public uint uID;
public uint uFlags;
public uint uCallbackMessage;
public IntPtr hIcon;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public string szTip;
}
// Functions
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr LoadImage(IntPtr hinst, string lpszName, uint uType, int cxDesired, int cyDesired, uint fuLoad);
[DllImport("shell32.dll")]
private static extern bool Shell_NotifyIcon(uint dwMessage, ref NOTIFYICONDATA lpdata);
[DllImport("user32.dll")]
private static extern bool GetCursorPos(out POINT lpPoint);
[DllImport("user32.dll")]
private static extern IntPtr CreatePopupMenu();
[DllImport("user32.dll")]
private static extern bool AppendMenu(IntPtr hMenu, uint uFlags, uint uIDNewItem, string lpNewItem);
[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern int TrackPopupMenu(IntPtr hMenu, uint uFlags, int x, int y, int nReserved, IntPtr hWnd, IntPtr prcRect);
[DllImport("user32.dll")]
private static extern bool DestroyMenu(IntPtr hMenu);
[DllImport("Comctl32.dll", SetLastError = true)]
private static extern bool SetWindowSubclass(IntPtr hWnd, SUBCLASSPROC pfnSubclass, uint uIdSubclass, int dwRefData);
[DllImport("Comctl32.dll", SetLastError = true)]
private static extern int DefSubclassProc(IntPtr hWnd, uint uMsg, IntPtr wParam, IntPtr lParam);
#endregion
}
}