-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrayApplication.cs
More file actions
421 lines (362 loc) · 17.5 KB
/
TrayApplication.cs
File metadata and controls
421 lines (362 loc) · 17.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
using DefaultBrowserWindows.Models;
using DefaultBrowserWindows.Services;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
namespace DefaultBrowserWindows
{
public class TrayApplication : Control, IDisposable
{
private NotifyIcon _notifyIcon = null!;
private ContextMenuStrip _contextMenu = null!;
private BrowserService _browserService;
private ConfigurationService _configService;
private RegistryService _registryService;
private List<BrowserInfo> _installedBrowsers = null!;
private System.Windows.Forms.Timer _refreshTimer = null!;
public TrayApplication()
{
_browserService = new BrowserService();
_configService = new ConfigurationService();
_registryService = new RegistryService();
// Create the control handle to enable Invoke calls
this.CreateControl();
InitializeTrayIcon();
RefreshBrowserList();
// Handle command line arguments
var args = Environment.GetCommandLineArgs();
if (args.Length > 1)
{
HandleCommandLineArguments(args);
}
// Set up refresh timer
_refreshTimer = new System.Windows.Forms.Timer();
_refreshTimer.Interval = 30000; // Refresh every 30 seconds
_refreshTimer.Tick += (s, e) => RefreshBrowserList();
_refreshTimer.Start();
}
private void InitializeTrayIcon()
{
_contextMenu = new ContextMenuStrip();
_notifyIcon = new NotifyIcon()
{
Icon = CreateDefaultIcon(),
ContextMenuStrip = _contextMenu,
Text = "Default Browser Windows",
Visible = true
};
_notifyIcon.DoubleClick += (s, e) => ShowBrowserSelection();
}
private Icon CreateDefaultIcon()
{
// Create a simple icon programmatically
var bitmap = new Bitmap(16, 16);
using (var g = Graphics.FromImage(bitmap))
{
g.Clear(Color.Transparent);
g.FillEllipse(Brushes.Blue, 2, 2, 12, 12);
g.DrawString("B", new Font("Arial", 8, FontStyle.Bold), Brushes.White, 4, 2);
}
return Icon.FromHandle(bitmap.GetHicon());
}
private void RefreshBrowserList()
{
_installedBrowsers = _browserService.GetInstalledBrowsers();
BuildContextMenu();
UpdateTrayIcon();
}
private void BuildContextMenu()
{
_contextMenu.Items.Clear();
// Browser selection section
_contextMenu.Items.Add(new ToolStripLabel("Select Browser:") { Font = new Font(_contextMenu.Font, FontStyle.Bold) });
_contextMenu.Items.Add(new ToolStripSeparator());
var selectedBrowser = _installedBrowsers.FirstOrDefault(b =>
b.Name.Equals(_configService.Configuration.SelectedBrowserName, StringComparison.OrdinalIgnoreCase));
foreach (var browser in _installedBrowsers)
{
var item = new ToolStripMenuItem(browser.DisplayName)
{
Tag = browser,
Checked = browser.Equals(selectedBrowser)
};
item.Click += BrowserMenuItem_Click;
_contextMenu.Items.Add(item);
}
_contextMenu.Items.Add(new ToolStripSeparator());
// Settings section
var settingsItem = new ToolStripMenuItem("Settings...");
settingsItem.Click += (s, e) => ShowSettings();
_contextMenu.Items.Add(settingsItem);
// Registration section
var isRegistered = _registryService.IsRegisteredAsDefaultBrowser();
var isActualDefault = _registryService.IsActuallyDefaultBrowser();
var registerItem = new ToolStripMenuItem(isRegistered ? "Unregister as Default Browser" : "Register as Default Browser");
registerItem.Click += RegisterMenuItem_Click;
_contextMenu.Items.Add(registerItem);
// Status indicator
var statusText = isRegistered ? (isActualDefault ? "✓ Active Default Browser" : "⚠ Registered but not default") : "✗ Not registered";
var statusItem = new ToolStripMenuItem(statusText)
{
Enabled = false,
ForeColor = isActualDefault ? Color.Green : (isRegistered ? Color.Orange : Color.Red)
};
_contextMenu.Items.Add(statusItem);
// If registered but not set as default on Windows 10+, add helper menu
if (isRegistered && !isActualDefault && _registryService.IsWindows10OrLater())
{
var helpItem = new ToolStripMenuItem("Open Windows Settings");
helpItem.Click += (s, e) => _registryService.OpenDefaultAppsSettings();
_contextMenu.Items.Add(helpItem);
}
_contextMenu.Items.Add(new ToolStripSeparator());
// Diagnostics section
var diagnosticsItem = new ToolStripMenuItem("Diagnostics");
var statusDetailsItem = new ToolStripMenuItem("Show Association Details");
statusDetailsItem.Click += (s, e) => ShowAssociationDetails();
diagnosticsItem.DropDownItems.Add(statusDetailsItem);
if (_registryService.IsEdgeInterferenceDetected())
{
var edgeItem = new ToolStripMenuItem("⚠ Edge Interference Detected");
edgeItem.Click += (s, e) => ShowEdgeInterferenceHelp();
diagnosticsItem.DropDownItems.Add(edgeItem);
}
_contextMenu.Items.Add(diagnosticsItem);
_contextMenu.Items.Add(new ToolStripSeparator());
// About and Exit
var aboutItem = new ToolStripMenuItem("About");
aboutItem.Click += (s, e) => ShowAbout();
_contextMenu.Items.Add(aboutItem);
var exitItem = new ToolStripMenuItem("Exit");
exitItem.Click += (s, e) => Application.Exit();
_contextMenu.Items.Add(exitItem);
}
private void BrowserMenuItem_Click(object? sender, EventArgs e)
{
if (sender is ToolStripMenuItem item && item.Tag is BrowserInfo browser)
{
_configService.SetSelectedBrowser(browser);
RefreshBrowserList();
if (_configService.Configuration.ShowNotifications)
{
_notifyIcon.ShowBalloonTip(2000, "Browser Changed",
$"Default browser set to {browser.DisplayName}", ToolTipIcon.Info);
}
}
}
private void RegisterMenuItem_Click(object? sender, EventArgs e)
{
var isRegistered = _registryService.IsRegisteredAsDefaultBrowser();
if (isRegistered)
{
if (MessageBox.Show("Are you sure you want to unregister Default Browser Windows as the default browser?",
"Unregister Default Browser", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_registryService.UnregisterAsDefaultBrowser();
RefreshBrowserList();
}
}
else
{
if (!_registryService.IsRunningAsAdministrator())
{
var result = MessageBox.Show("Administrator privileges are required to register as default browser. Restart as administrator?",
"Administrator Required", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (result == DialogResult.Yes)
{
_registryService.RestartAsAdministrator();
Application.Exit();
}
}
else
{
if (_registryService.RegisterAsDefaultBrowser())
{
var message = "Successfully registered as default browser.";
if (_registryService.IsWindows10OrLater())
{
message += "\n\nFor Windows 10+, you need to manually set the default browser:";
message += "\n1. Click 'Open Settings' to go to Default Apps";
message += "\n2. Select 'Default Browser Windows' as your web browser";
var result = MessageBox.Show(message + "\n\nOpen Settings now?",
"Registration Complete - Manual Setup Required",
MessageBoxButtons.YesNo, MessageBoxIcon.Information);
if (result == DialogResult.Yes)
{
_registryService.OpenDefaultAppsSettings();
}
}
else
{
MessageBox.Show(message, "Registration Complete",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
RefreshBrowserList();
}
else
{
MessageBox.Show("Failed to register as default browser. Please try running as administrator.",
"Registration Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void ShowBrowserSelection()
{
using (var form = new BrowserSelectionForm(_installedBrowsers, _configService))
{
if (form.ShowDialog() == DialogResult.OK)
{
RefreshBrowserList();
}
}
}
private void ShowSettings()
{
using (var form = new SettingsForm(_configService))
{
form.ShowDialog();
}
}
private void ShowAbout()
{
MessageBox.Show(
"Default Browser Windows v1.0\n\n" +
"A Windows system tray app to intelligently control your default web browser.\n\n" +
"Similar to DefaultBrowser for macOS, this tool allows you to quickly switch between browsers " +
"and opens links with your most recently selected browser.\n\n" +
"© 2024",
"About Default Browser Windows",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
private void UpdateTrayIcon()
{
var selectedBrowser = _installedBrowsers.FirstOrDefault(b =>
b.Name.Equals(_configService.Configuration.SelectedBrowserName, StringComparison.OrdinalIgnoreCase));
var tooltip = selectedBrowser != null
? $"Default Browser: {selectedBrowser.DisplayName}"
: "Default Browser Windows - No browser selected";
_notifyIcon.Text = tooltip.Length > 63 ? tooltip.Substring(0, 60) + "..." : tooltip;
}
private void ShowAssociationDetails()
{
var details = _registryService.GetBrowserAssociationDetails();
MessageBox.Show(details, "Browser Association Details",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void ShowEdgeInterferenceHelp()
{
var message = "Microsoft Edge interference detected!\n\n" +
"Windows may be redirecting some links to Edge regardless of your default browser setting. " +
"This is a Windows feature that cannot be disabled through this application.\n\n" +
"To work around this:\n" +
"1. Open Windows Settings > Apps > Default apps\n" +
"2. Ensure 'Default Browser Windows' is selected as your web browser\n" +
"3. Check protocol associations for HTTP and HTTPS\n\n" +
"Some Windows updates may reset these settings.";
var result = MessageBox.Show(message + "\n\nOpen Windows Settings now?",
"Edge Interference Help", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (result == DialogResult.Yes)
{
_registryService.OpenProtocolAssociationSettings();
}
}
private void HandleCommandLineArguments(string[] args)
{
for (int i = 1; i < args.Length; i++)
{
var arg = args[i];
if (arg.Equals("--register", StringComparison.OrdinalIgnoreCase))
{
if (_registryService.RegisterAsDefaultBrowser())
{
MessageBox.Show("Successfully registered as default browser.",
"Registration Complete", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Failed to register as default browser.",
"Registration Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
Application.Exit();
return;
}
else if (arg.StartsWith("-") && (arg.Contains("showicons") || arg.Contains("hideicons") || arg.Contains("reinstall")))
{
// Handle Windows registration commands
_registryService.HandleRegistrationCommand(arg);
Application.Exit();
return;
}
else if (arg.StartsWith("http://") || arg.StartsWith("https://") || arg.StartsWith("ftp://") || arg.EndsWith(".html") || arg.EndsWith(".htm"))
{
// Handle URL or file
var selectedBrowser = _installedBrowsers.FirstOrDefault(b =>
b.Name.Equals(_configService.Configuration.SelectedBrowserName, StringComparison.OrdinalIgnoreCase));
if (selectedBrowser != null)
{
_browserService.LaunchUrl(arg, selectedBrowser);
}
else
{
_browserService.LaunchUrl(arg);
}
return; // Don't show tray icon for URL handling
}
}
}
public void HandleExternalCommand(string[] args)
{
// Handle command line arguments from another instance
for (int i = 0; i < args.Length; i++)
{
var arg = args[i];
if (arg.Equals("--register", StringComparison.OrdinalIgnoreCase))
{
if (_registryService.RegisterAsDefaultBrowser())
{
_notifyIcon.ShowBalloonTip(3000, "Registration Complete",
"Successfully registered as default browser.", ToolTipIcon.Info);
}
else
{
_notifyIcon.ShowBalloonTip(3000, "Registration Failed",
"Failed to register as default browser.", ToolTipIcon.Error);
}
return;
}
else if (arg.StartsWith("-") && (arg.Contains("showicons") || arg.Contains("hideicons") || arg.Contains("reinstall")))
{
// Handle Windows registration commands
_registryService.HandleRegistrationCommand(arg);
return;
}
else if (arg.StartsWith("http://") || arg.StartsWith("https://") || arg.StartsWith("ftp://") || arg.EndsWith(".html") || arg.EndsWith(".htm"))
{
// Handle URL or file
var selectedBrowser = _installedBrowsers.FirstOrDefault(b =>
b.Name.Equals(_configService.Configuration.SelectedBrowserName, StringComparison.OrdinalIgnoreCase));
if (selectedBrowser != null)
{
_browserService.LaunchUrl(arg, selectedBrowser);
}
else
{
_browserService.LaunchUrl(arg);
}
return;
}
}
}
public new void Dispose()
{
_refreshTimer?.Dispose();
_notifyIcon?.Dispose();
_contextMenu?.Dispose();
}
}
}