-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathApp.xaml.cs
More file actions
1437 lines (1285 loc) · 55.9 KB
/
App.xaml.cs
File metadata and controls
1437 lines (1285 loc) · 55.9 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;
using System.Diagnostics;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using Hardcodet.Wpf.TaskbarNotification;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using System.Threading.Tasks;
using System.Windows.Input;
namespace TrayChrome
{
public partial class App : Application
{
private TaskbarIcon? trayIcon;
private MainWindow? mainWindow;
private static int instanceCounter = 0;
private int currentInstanceId;
private List<Bookmark> bookmarks = new List<Bookmark>();
private string bookmarksFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bookmarks.json");
// 全局快捷键管理器
private GlobalHotKeyManager? hotKeyManager;
private AppSettings appSettings = new AppSettings();
private string settingsFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "settings.json");
private FileSystemWatcher? settingsWatcher;
// 验证URL格式的辅助方法
private bool IsValidUrl(string url)
{
return Uri.TryCreate(url, UriKind.Absolute, out Uri? result)
&& (result.Scheme == Uri.UriSchemeHttp || result.Scheme == Uri.UriSchemeHttps);
}
// 解析窗口大小的辅助方法
private bool TryParseSize(string sizeValue, out double width, out double height)
{
width = 0;
height = 0;
if (string.IsNullOrEmpty(sizeValue))
return false;
string[] parts = sizeValue.Split('x', 'X', '*');
if (parts.Length != 2)
return false;
if (double.TryParse(parts[0], out width) && double.TryParse(parts[1], out height))
{
// 验证尺寸范围
if (width >= 200 && width <= 3840 && height >= 150 && height <= 2160)
{
return true;
}
}
return false;
}
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
// 分配实例ID
currentInstanceId = ++instanceCounter;
// 解析命令行参数
string? startupUrl = null;
bool shouldOpen = false; // 默认不直接显示窗口
bool shouldUseCleanMode = false; // 默认不使用超级简洁模式
bool shouldForceUncleanMode = false; // 是否强制禁用超级极简模式
bool shouldShowHelp = false; // 是否显示帮助信息
double? customWidth = null; // 自定义窗口宽度
double? customHeight = null; // 自定义窗口高度
if (e.Args.Length > 0)
{
// 支持多种参数格式
for (int i = 0; i < e.Args.Length; i++)
{
string arg = e.Args[i];
// 支持 --url=https://example.com 格式
if (arg.StartsWith("--url=", StringComparison.OrdinalIgnoreCase))
{
startupUrl = arg.Substring(6);
}
// 支持 --url https://example.com 格式
else if (arg.Equals("--url", StringComparison.OrdinalIgnoreCase) && i + 1 < e.Args.Length)
{
startupUrl = e.Args[i + 1];
i++; // 跳过下一个参数,因为已经作为URL使用了
}
// 支持 --open 格式
else if (arg.Equals("--open", StringComparison.OrdinalIgnoreCase))
{
shouldOpen = true;
}
// 支持 --clean 格式(启用超级极简模式)
else if (arg.Equals("--clean", StringComparison.OrdinalIgnoreCase))
{
shouldUseCleanMode = true;
}
// 支持 --unclean 格式(强制禁用超级极简模式)
else if (arg.Equals("--unclean", StringComparison.OrdinalIgnoreCase))
{
shouldForceUncleanMode = true;
}
// 支持 --help 格式
else if (arg.Equals("--help", StringComparison.OrdinalIgnoreCase) || arg.Equals("-h", StringComparison.OrdinalIgnoreCase))
{
shouldShowHelp = true;
}
// 支持 --size=480x320 格式
else if (arg.StartsWith("--size=", StringComparison.OrdinalIgnoreCase))
{
string sizeValue = arg.Substring(7);
if (TryParseSize(sizeValue, out double width, out double height))
{
customWidth = width;
customHeight = height;
}
}
// 支持 --size 480x320 格式
else if (arg.Equals("--size", StringComparison.OrdinalIgnoreCase) && i + 1 < e.Args.Length)
{
string sizeValue = e.Args[i + 1];
if (TryParseSize(sizeValue, out double width, out double height))
{
customWidth = width;
customHeight = height;
}
i++; // 跳过下一个参数,因为已经作为size使用了
}
// 支持直接传入URL(如果看起来像URL)
else if (IsValidUrl(arg))
{
startupUrl = arg;
}
}
}
// 如果需要显示帮助信息
if (shouldShowHelp)
{
ShowHelpMessage();
Shutdown();
return;
}
// 创建托盘图标
trayIcon = (TaskbarIcon)FindResource("TrayIcon");
// 更新托盘图标标识
if (trayIcon != null)
{
trayIcon.ToolTipText = $"Tray Chrome Browser - 实例 {currentInstanceId}";
}
// 创建主窗口,传入启动参数
mainWindow = new MainWindow(startupUrl, shouldUseCleanMode, shouldForceUncleanMode, customWidth, customHeight);
// 根据 --open 参数决定是否显示窗口
if (shouldOpen)
{
// 模拟托盘图标点击事件的逻辑
mainWindow.ShowWithAnimation();
mainWindow.WindowState = WindowState.Normal;
mainWindow.Activate();
}
else
{
mainWindow.Hide();
}
// 订阅标题变化事件
mainWindow.TitleChanged += OnMainWindowTitleChanged;
// 更新托盘菜单中超级极简模式的状态
UpdateSuperMinimalModeMenuState();
UpdateAnimationMenuState();
UpdateAdBlockMenuState();
// 加载收藏夹并刷新托盘菜单
LoadBookmarks();
RefreshTrayBookmarkMenu();
// 加载设置并初始化全局快捷键
LoadSettings();
InitializeGlobalHotKey();
InitializeSettingsWatcher();
// 隐藏主窗口,只显示托盘图标
MainWindow = mainWindow;
if (!shouldOpen)
{
MainWindow.WindowState = WindowState.Minimized;
}
MainWindow.ShowInTaskbar = false;
}
private void TrayIcon_TrayLeftMouseUp(object sender, RoutedEventArgs e)
{
if (mainWindow != null)
{
if (mainWindow.IsVisible)
{
mainWindow.HideWithAnimation();
}
else
{
mainWindow.ShowWithAnimation();
mainWindow.WindowState = WindowState.Normal;
mainWindow.Activate();
}
}
}
private void AddInstance_Click(object sender, RoutedEventArgs e)
{
try
{
// 启动新的应用程序实例
string currentExecutable = Process.GetCurrentProcess().MainModule?.FileName ?? "";
if (!string.IsNullOrEmpty(currentExecutable))
{
Process.Start(currentExecutable);
}
}
catch (Exception ex)
{
MessageBox.Show($"启动新实例失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private void TrayIcon_TrayMiddleMouseUp(object sender, RoutedEventArgs e)
{
// Ctrl + 中键:增加实例;普通中键:不做操作
try
{
if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
{
string currentExecutable = Process.GetCurrentProcess().MainModule?.FileName ?? "";
if (!string.IsNullOrEmpty(currentExecutable))
{
Process.Start(currentExecutable);
}
}else{
Application.Current.Shutdown();
}
}
catch (Exception ex)
{
MessageBox.Show($"启动新实例失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private void RestartInstance_Click(object sender, RoutedEventArgs e)
{
try
{
string args = "--open";
if (mainWindow?.webView?.CoreWebView2 != null)
{
string currentUrl = mainWindow.webView.CoreWebView2.Source;
if (!string.IsNullOrEmpty(currentUrl))
{
args += $" --url \"{currentUrl}\"";
}
}
// 启动新的应用程序实例
string currentExecutable = Process.GetCurrentProcess().MainModule?.FileName ?? "";
if (!string.IsNullOrEmpty(currentExecutable))
{
Process.Start(currentExecutable, args);
}
// 关闭当前实例
Application.Current.Shutdown();
}
catch (Exception ex)
{
MessageBox.Show($"重启实例失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private void CloseInstance_Click(object sender, RoutedEventArgs e)
{
// 关闭当前实例
Application.Current.Shutdown();
}
private void SuperMinimalMode_Click(object sender, RoutedEventArgs e)
{
if (sender is MenuItem menuItem && mainWindow != null)
{
// 切换超级极简模式状态
mainWindow.ToggleSuperMinimalMode(menuItem.IsChecked);
// 同步菜单项状态到主窗口的超级极简模式状态
UpdateSuperMinimalModeMenuState();
}
}
private void Animation_Click(object sender, RoutedEventArgs e)
{
if (sender is MenuItem menuItem && mainWindow != null)
{
// 切换动画设置
mainWindow.ToggleAnimation(menuItem.IsChecked);
UpdateAnimationMenuState();
}
}
private void AdBlock_Click(object sender, RoutedEventArgs e)
{
if (sender is MenuItem menuItem && mainWindow != null)
{
// 切换广告拦截
mainWindow.ToggleAdBlock(menuItem.IsChecked);
UpdateAdBlockMenuState();
}
}
private void AdBlockSettings_Click(object sender, RoutedEventArgs e)
{
if (mainWindow != null)
{
mainWindow.ShowAdBlockSettings();
UpdateAdBlockMenuState();
}
}
private void OpenSettings_Click(object sender, RoutedEventArgs e)
{
try
{
if (mainWindow != null)
{
// 确保主窗口已经显示过(即使现在是隐藏的),这样才能设置Owner
if (!mainWindow.IsLoaded)
{
mainWindow.Show();
mainWindow.Hide();
}
var settingsWindow = new SettingsWindow(appSettings, mainWindow, this);
// 订阅收藏夹更新事件
settingsWindow.BookmarksUpdated += OnBookmarksUpdated;
// 订阅窗口关闭事件,在关闭时更新设置
settingsWindow.Closed += (s, args) =>
{
// 对于非模态窗口,使用SettingsSaved属性来判断是否保存了设置
if (settingsWindow.SettingsSaved)
{
// 设置已保存,重新加载全局快捷键
ReloadGlobalHotKey();
// 更新菜单状态
UpdateSuperMinimalModeMenuState();
UpdateAnimationMenuState();
UpdateAdBlockMenuState();
}
// 取消订阅事件
settingsWindow.BookmarksUpdated -= OnBookmarksUpdated;
};
// 使用非模态窗口,不阻塞主线程
settingsWindow.Show();
}
}
catch (Exception ex)
{
MessageBox.Show($"打开设置窗口失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
public void OnBookmarksUpdated(object? sender, EventArgs e)
{
// 重新加载收藏夹并刷新托盘菜单 (LoadBookmarks 内部会调用 RefreshTrayBookmarkMenu)
LoadBookmarks();
// 同时更新主窗口的收藏夹菜单
mainWindow?.LoadBookmarks();
}
private void UpdateAdBlockMenuState()
{
if (trayIcon?.ContextMenu != null && mainWindow != null)
{
var menuItem = trayIcon.ContextMenu.Items.OfType<MenuItem>()
.FirstOrDefault(item => item.Name == "AdBlockMenuItem");
if (menuItem != null)
{
menuItem.IsChecked = mainWindow.IsAdBlockEnabled;
}
}
}
private void UpdateSuperMinimalModeMenuState()
{
if (trayIcon?.ContextMenu != null && mainWindow != null)
{
var menuItem = trayIcon.ContextMenu.Items.OfType<MenuItem>()
.FirstOrDefault(item => item.Name == "SuperMinimalModeMenuItem");
if (menuItem != null)
{
menuItem.IsChecked = mainWindow.IsSuperMinimalMode;
}
}
}
private void UpdateAnimationMenuState()
{
if (trayIcon?.ContextMenu != null && mainWindow != null)
{
var menuItem = trayIcon.ContextMenu.Items.OfType<MenuItem>()
.FirstOrDefault(item => item.Name == "AnimationMenuItem");
if (menuItem != null)
{
menuItem.IsChecked = mainWindow.IsAnimationEnabled;
}
}
}
public void SetIcon_Click(object? sender, RoutedEventArgs? e)
{
string? iconType = null;
if (sender is MenuItem menuItem && menuItem.Tag is string tag)
{
iconType = tag;
}
else if (sender is RadioButton radioButton && radioButton.Tag is string radioTag)
{
iconType = radioTag;
}
if (!string.IsNullOrEmpty(iconType))
{
try
{
string iconPath;
switch (iconType)
{
case "default":
iconPath = "pack://application:,,,/Resources/Ampeross-Ampola-Chrome.ico";
break;
case "dingding":
iconPath = "pack://application:,,,/Resources/alternative-icons/dingding.ico";
break;
case "feishu":
iconPath = "pack://application:,,,/Resources/alternative-icons/feishu.ico";
break;
case "wecom":
iconPath = "pack://application:,,,/Resources/alternative-icons/wecom.ico";
break;
case "weixin":
iconPath = "pack://application:,,,/Resources/alternative-icons/weixin.ico";
break;
default:
return;
}
SetApplicationIcon(iconPath);
SaveIconSetting(iconType, iconPath);
}
catch (Exception ex)
{
MessageBox.Show($"设置图标失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
}
private void SetCustomIcon_Click(object sender, RoutedEventArgs e)
{
try
{
// 创建文件选择对话框
var openFileDialog = new Microsoft.Win32.OpenFileDialog();
// 设置对话框属性
openFileDialog.Title = "选择图标文件";
openFileDialog.Filter = "图标文件 (*.ico)|*.ico|PNG图片 (*.png)|*.png|所有文件 (*.*)|*.*";
openFileDialog.FilterIndex = 1;
openFileDialog.CheckFileExists = true;
openFileDialog.CheckPathExists = true;
openFileDialog.Multiselect = false;
openFileDialog.RestoreDirectory = true;
// 设置初始目录为用户的桌面
openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
// 显示对话框并获取结果
Window owner = null;
if (mainWindow != null && mainWindow.IsVisible)
{
owner = mainWindow;
}
else
{
// 如果主窗口不可见,尝试获取当前活动窗口
owner = Application.Current.MainWindow;
}
bool? dialogResult;
if (owner != null)
{
dialogResult = openFileDialog.ShowDialog(owner);
}
else
{
dialogResult = openFileDialog.ShowDialog();
}
if (dialogResult == true && !string.IsNullOrEmpty(openFileDialog.FileName))
{
string selectedPath = openFileDialog.FileName;
// 验证文件是否存在和可读
if (!File.Exists(selectedPath))
{
MessageBox.Show("选择的文件不存在!", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
// 验证文件大小(不超过5MB)
var fileInfo = new FileInfo(selectedPath);
if (fileInfo.Length > 5 * 1024 * 1024)
{
MessageBox.Show("图标文件过大,请选择小于5MB的文件!", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
// 验证图标文件是否有效
if (!IsValidIconFile(selectedPath))
{
MessageBox.Show("选择的文件不是有效的图标文件!", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
// 复制图标到应用程序目录
string customIconsDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Resources", "custom-icons");
Directory.CreateDirectory(customIconsDir);
string fileName = $"custom_{DateTime.Now:yyyyMMddHHmmss}{Path.GetExtension(selectedPath)}";
string targetPath = Path.Combine(customIconsDir, fileName);
File.Copy(selectedPath, targetPath, true);
SetApplicationIcon(targetPath);
SaveIconSetting("custom", targetPath);
MessageBox.Show("自定义图标设置成功!", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
catch (Exception ex)
{
// 显示详细的错误信息用于调试
string errorMessage = $"错误类型: {ex.GetType().Name}\n错误信息: {ex.Message}\n堆栈跟踪: {ex.StackTrace}";
MessageBox.Show(errorMessage, "详细错误信息", MessageBoxButton.OK, MessageBoxImage.Error);
// 同时输出到调试控制台
System.Diagnostics.Debug.WriteLine($"SetCustomIcon_Click异常详情: {ex}");
}
}
private bool IsValidIconFile(string filePath)
{
try
{
string extension = Path.GetExtension(filePath).ToLower();
if (extension == ".ico")
{
// 尝试创建Icon对象来验证ICO文件
using (var icon = new System.Drawing.Icon(filePath))
{
return icon.Width > 0 && icon.Height > 0;
}
}
else if (extension == ".png")
{
// 尝试创建BitmapImage来验证PNG文件
var bitmap = new System.Windows.Media.Imaging.BitmapImage();
bitmap.BeginInit();
bitmap.UriSource = new Uri(filePath, UriKind.Absolute);
bitmap.EndInit();
return bitmap.PixelWidth > 0 && bitmap.PixelHeight > 0;
}
return false;
}
catch
{
return false;
}
}
public void SetApplicationIcon(string iconPath)
{
try
{
// 设置托盘图标
if (trayIcon != null)
{
if (iconPath.StartsWith("pack://"))
{
// 使用资源图标
var iconUri = new Uri(iconPath);
var iconStream = Application.GetResourceStream(iconUri);
if (iconStream != null)
{
// 需要重新创建流,因为Icon构造函数会关闭流
var memoryStream = new MemoryStream();
iconStream.Stream.CopyTo(memoryStream);
memoryStream.Position = 0;
// 释放旧图标
trayIcon.Icon?.Dispose();
trayIcon.Icon = new System.Drawing.Icon(memoryStream);
}
}
else if (File.Exists(iconPath))
{
// 使用文件图标
string extension = Path.GetExtension(iconPath).ToLower();
if (extension == ".ico")
{
// 释放旧图标
trayIcon.Icon?.Dispose();
trayIcon.Icon = new System.Drawing.Icon(iconPath);
}
else if (extension == ".png")
{
// 将PNG转换为Icon
using (var bitmap = new System.Drawing.Bitmap(iconPath))
{
var hIcon = bitmap.GetHicon();
// 释放旧图标
trayIcon.Icon?.Dispose();
trayIcon.Icon = System.Drawing.Icon.FromHandle(hIcon);
}
}
}
}
// 设置窗口图标
if (mainWindow != null)
{
if (iconPath.StartsWith("pack://"))
{
var iconUri = new Uri(iconPath);
var bitmapImage = new System.Windows.Media.Imaging.BitmapImage();
bitmapImage.BeginInit();
bitmapImage.UriSource = iconUri;
bitmapImage.EndInit();
mainWindow.Icon = bitmapImage;
}
else if (File.Exists(iconPath))
{
var iconUri = new Uri(iconPath, UriKind.Absolute);
var bitmapImage = new System.Windows.Media.Imaging.BitmapImage();
bitmapImage.BeginInit();
bitmapImage.UriSource = iconUri;
bitmapImage.CacheOption = System.Windows.Media.Imaging.BitmapCacheOption.OnLoad;
bitmapImage.EndInit();
mainWindow.Icon = bitmapImage;
}
}
}
catch (ArgumentException argEx)
{
MessageBox.Show($"图标文件格式不正确: {argEx.Message}", "格式错误", MessageBoxButton.OK, MessageBoxImage.Error);
}
catch (OutOfMemoryException)
{
MessageBox.Show("内存不足,无法加载图标文件!", "内存错误", MessageBoxButton.OK, MessageBoxImage.Error);
}
catch (Exception ex)
{
MessageBox.Show($"应用图标失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
public void SaveIconSetting(string iconType, string iconPath)
{
try
{
string settingsFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "icon-settings.json");
var settings = new
{
IconType = iconType,
IconPath = iconPath,
LastUpdated = DateTime.Now
};
string json = JsonSerializer.Serialize(settings, new JsonSerializerOptions { WriteIndented = true });
File.WriteAllText(settingsFile, json);
}
catch (Exception ex)
{
// 静默处理保存错误,不影响图标设置
System.Diagnostics.Debug.WriteLine($"保存图标设置失败: {ex.Message}");
}
}
private void LoadIconSetting()
{
try
{
string settingsFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "icon-settings.json");
if (File.Exists(settingsFile))
{
string json = File.ReadAllText(settingsFile);
var settings = JsonSerializer.Deserialize<JsonElement>(json);
if (settings.TryGetProperty("IconPath", out var iconPathElement))
{
string iconPath = iconPathElement.GetString() ?? "";
if (!string.IsNullOrEmpty(iconPath))
{
SetApplicationIcon(iconPath);
}
}
}
}
catch (Exception ex)
{
// 静默处理加载错误,使用默认图标
System.Diagnostics.Debug.WriteLine($"加载图标设置失败: {ex.Message}");
}
}
private void OnMainWindowTitleChanged(string title)
{
if (trayIcon != null)
{
// 更新托盘图标的提示文本,只显示当前网页标题
trayIcon.ToolTipText = title;
}
}
protected override void OnExit(ExitEventArgs e)
{
// 取消订阅事件
if (mainWindow != null)
{
mainWindow.TitleChanged -= OnMainWindowTitleChanged;
}
// 清理全局快捷键资源
hotKeyManager?.Dispose();
// 清理文件监听器
settingsWatcher?.Dispose();
trayIcon?.Dispose();
base.OnExit(e);
}
private void AddBookmarkFromTray_Click(object sender, RoutedEventArgs e)
{
if (mainWindow?.webView?.CoreWebView2 != null)
{
string currentUrl = mainWindow.webView.CoreWebView2.Source;
string currentTitle = mainWindow.webView.CoreWebView2.DocumentTitle;
if (!string.IsNullOrEmpty(currentUrl) && !bookmarks.Any(b => b.Url.Equals(currentUrl, StringComparison.OrdinalIgnoreCase)))
{
var newBookmark = new Bookmark
{
Title = !string.IsNullOrEmpty(currentTitle) ? currentTitle : currentUrl,
Url = currentUrl
};
bookmarks.Add(newBookmark);
SaveBookmarks();
RefreshTrayBookmarkMenu();
MessageBox.Show($"已添加到收藏夹: {newBookmark.Title}", "收藏夹", MessageBoxButton.OK, MessageBoxImage.Information);
}
else
{
MessageBox.Show("该页面已在收藏夹中或无效", "收藏夹", MessageBoxButton.OK, MessageBoxImage.Warning);
}
}
}
private void EditBookmarkFromTray_Click(object sender, RoutedEventArgs e)
{
try
{
if (!File.Exists(bookmarksFilePath))
{
SaveBookmarks(); // 创建文件
}
string configFolder = Path.GetDirectoryName(bookmarksFilePath);
Process.Start(new ProcessStartInfo
{
FileName = "explorer.exe",
Arguments = configFolder,
UseShellExecute = true
});
}
catch (Exception ex)
{
MessageBox.Show($"打开收藏夹文件夹失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private void CreateDesktopShortcut_Click(object sender, RoutedEventArgs e)
{
try
{
// 获取当前页面的URL
string currentUrl = GetCurrentPageUrl();
if (string.IsNullOrEmpty(currentUrl))
{
MessageBox.Show("无法获取当前页面URL,请确保页面已加载完成。", "错误", MessageBoxButton.OK, MessageBoxImage.Warning);
return;
}
// 获取当前页面的标题
string pageTitle = GetCurrentPageTitle();
if (string.IsNullOrEmpty(pageTitle))
{
pageTitle = "网页快捷方式";
}
// 创建桌面快捷方式
CreateDesktopShortcut(currentUrl, pageTitle);
MessageBox.Show($"桌面快捷方式 \"{pageTitle}\" 创建成功!", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
}
catch (Exception ex)
{
MessageBox.Show($"创建桌面快捷方式失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private void OpenGithub_Click(object sender, RoutedEventArgs e)
{
try
{
Process.Start(new ProcessStartInfo
{
FileName = "https://github.com/cornradio/tray-chrome",
UseShellExecute = true
});
}
catch (Exception ex)
{
MessageBox.Show($"打开 GitHub 链接失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private string GetCurrentPageUrl()
{
try
{
if (mainWindow?.webView?.CoreWebView2 != null)
{
return mainWindow.webView.CoreWebView2.Source;
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"获取当前页面URL失败: {ex.Message}");
}
return string.Empty;
}
private string GetCurrentPageTitle()
{
try
{
if (mainWindow?.webView?.CoreWebView2 != null)
{
return mainWindow.webView.CoreWebView2.DocumentTitle;
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"获取当前页面标题失败: {ex.Message}");
}
return string.Empty;
}
private void CreateDesktopShortcut(string url, string title)
{
try
{
// 获取桌面路径
string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
// 清理文件名中的非法字符
string fileName = title;
char[] invalidChars = Path.GetInvalidFileNameChars();
foreach (char c in invalidChars)
{
fileName = fileName.Replace(c, '_');
}
// 限制文件名长度
if (fileName.Length > 50)
{
fileName = fileName.Substring(0, 50);
}
string shortcutPath = Path.Combine(desktopPath, $"{fileName}.lnk");
// 如果文件已存在,添加数字后缀
int counter = 1;
string originalPath = shortcutPath;
while (System.IO.File.Exists(shortcutPath))
{
string nameWithoutExt = Path.GetFileNameWithoutExtension(originalPath);
shortcutPath = Path.Combine(desktopPath, $"{nameWithoutExt}({counter}).lnk");
counter++;
}
// 获取当前应用程序的路径
string appPath = Process.GetCurrentProcess().MainModule?.FileName ?? "";
if (string.IsNullOrEmpty(appPath))
{
throw new Exception("无法获取应用程序路径");
}
// 获取当前窗口大小
string sizeArgument = "";
if (mainWindow != null)
{
// 获取当前窗口的实际大小(四舍五入到整数)
int currentWidth = (int)Math.Round(mainWindow.ActualWidth);
int currentHeight = (int)Math.Round(mainWindow.ActualHeight);
// 确保尺寸在有效范围内
if (currentWidth >= 200 && currentWidth <= 3840 &&
currentHeight >= 150 && currentHeight <= 2160)
{
sizeArgument = $" --size {currentWidth}x{currentHeight}";
}
}
// 使用PowerShell创建Windows快捷方式
string psScript = $@"
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut('{shortcutPath.Replace("'", "''")}')
$Shortcut.TargetPath = '{appPath.Replace("'", "''")}'
$Shortcut.Arguments = '--url ""{url}"" --open{sizeArgument}'
$Shortcut.Description = 'TrayChrome - {title.Replace("'", "''")}'
$Shortcut.IconLocation = '{appPath.Replace("'", "''")}' + ',0'
$Shortcut.WorkingDirectory = '{Path.GetDirectoryName(appPath)?.Replace("'", "''")}'
$Shortcut.Save()
";
ProcessStartInfo psi = new ProcessStartInfo
{
FileName = "powershell.exe",
Arguments = $"-NoProfile -ExecutionPolicy Bypass -Command \"{psScript.Replace("\"", "\\\"")}\"",
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true
};
using (Process process = Process.Start(psi))
{
process?.WaitForExit();
if (process?.ExitCode != 0)
{
string error = process.StandardError.ReadToEnd();
throw new Exception($"PowerShell执行失败: {error}");
}
}
}
catch (Exception ex)
{
throw new Exception($"创建快捷方式文件失败: {ex.Message}");
}
}
public void LoadBookmarks()
{
try
{
Directory.CreateDirectory(Path.GetDirectoryName(bookmarksFilePath));
if (File.Exists(bookmarksFilePath))
{
var json = File.ReadAllText(bookmarksFilePath);
bookmarks = JsonSerializer.Deserialize<List<Bookmark>>(json) ?? new List<Bookmark>();
}
else