diff --git a/.gitignore b/.gitignore
index d1ef8415b127c7fa45411f5ec8fea582e409db5d..7f78fe30547e09822cfb476a4d62d0da10d26724 100644
--- a/.gitignore
+++ b/.gitignore
@@ -31,3 +31,4 @@ imgui.ini
7e644cf859a5e100a21ff67a63486ae0.json
__pycache__/
+csharp/BrowserTool/db/sites.db
diff --git a/csharp/BrowserTool/.cursorignore b/csharp/BrowserTool/.cursorignore
new file mode 100644
index 0000000000000000000000000000000000000000..02193e824d812970b354ba347cadac10a4cd070d
--- /dev/null
+++ b/csharp/BrowserTool/.cursorignore
@@ -0,0 +1,34 @@
+# Build outputs
+bin/
+obj/
+dist/
+build/
+
+# Dependencies
+node_modules/
+packages/
+.vs/
+
+# IDE files
+.vscode/
+.idea/
+
+# Logs and databases
+*.log
+*.sqlite
+*.db
+
+# Temporary files
+*.tmp
+*.temp
+*.swp
+*~
+
+# Large binary files
+*.zip
+*.rar
+*.7z
+*.tar
+*.gz
+*.iso
+*.img
\ No newline at end of file
diff --git a/csharp/BrowserTool/.gitattributes b/csharp/BrowserTool/.gitattributes
new file mode 100644
index 0000000000000000000000000000000000000000..3e85c301857b88299cc96696cce47f4b013644fd
--- /dev/null
+++ b/csharp/BrowserTool/.gitattributes
@@ -0,0 +1,72 @@
+*.7z filter=lfs diff=lfs merge=lfs -text
+*.db filter=lfs diff=lfs merge=lfs -text
+*.pdf filter=lfs diff=lfs merge=lfs -text
+**/data/img/*.txt filter=lfs diff=lfs merge=lfs -text
+src/WeChatOcrCpp/wco_data/**/* filter=lfs diff=lfs merge=lfs -text
+*.aps filter=lfs diff=lfs merge=lfs -text
+*.ico filter=lfs diff=lfs merge=lfs -text
+*.pgm filter=lfs diff=lfs merge=lfs -text
+*.exe filter=lfs diff=lfs merge=lfs -text
+*.dll filter=lfs diff=lfs merge=lfs -text
+*.lib filter=lfs diff=lfs merge=lfs -text
+*.exp filter=lfs diff=lfs merge=lfs -text
+data/img/*.txt filter=lfs diff=lfs merge=lfs -text
+*.ttf filter=lfs diff=lfs merge=lfs -text
+*.arrow filter=lfs diff=lfs merge=lfs -text
+*.bin filter=lfs diff=lfs merge=lfs -text
+*.bz2 filter=lfs diff=lfs merge=lfs -text
+*.ckpt filter=lfs diff=lfs merge=lfs -text
+*.ftz filter=lfs diff=lfs merge=lfs -text
+*.gz filter=lfs diff=lfs merge=lfs -text
+*.h5 filter=lfs diff=lfs merge=lfs -text
+*.joblib filter=lfs diff=lfs merge=lfs -text
+*.lfs.* filter=lfs diff=lfs merge=lfs -text
+*.lz4 filter=lfs diff=lfs merge=lfs -text
+*.mds filter=lfs diff=lfs merge=lfs -text
+*.mlmodel filter=lfs diff=lfs merge=lfs -text
+*.model filter=lfs diff=lfs merge=lfs -text
+*.msgpack filter=lfs diff=lfs merge=lfs -text
+*.npy filter=lfs diff=lfs merge=lfs -text
+*.npz filter=lfs diff=lfs merge=lfs -text
+*.onnx filter=lfs diff=lfs merge=lfs -text
+*.ot filter=lfs diff=lfs merge=lfs -text
+*.parquet filter=lfs diff=lfs merge=lfs -text
+*.pb filter=lfs diff=lfs merge=lfs -text
+*.pickle filter=lfs diff=lfs merge=lfs -text
+*.pkl filter=lfs diff=lfs merge=lfs -text
+*.pt filter=lfs diff=lfs merge=lfs -text
+*.pth filter=lfs diff=lfs merge=lfs -text
+*.rar filter=lfs diff=lfs merge=lfs -text
+*.safetensors filter=lfs diff=lfs merge=lfs -text
+saved_model/**/* filter=lfs diff=lfs merge=lfs -text
+*.tar.* filter=lfs diff=lfs merge=lfs -text
+*.tar filter=lfs diff=lfs merge=lfs -text
+*.tflite filter=lfs diff=lfs merge=lfs -text
+*.tgz filter=lfs diff=lfs merge=lfs -text
+*.wasm filter=lfs diff=lfs merge=lfs -text
+*.xz filter=lfs diff=lfs merge=lfs -text
+*.zip filter=lfs diff=lfs merge=lfs -text
+*.zst filter=lfs diff=lfs merge=lfs -text
+*tfevents* filter=lfs diff=lfs merge=lfs -text
+# Audio files - uncompressed
+*.pcm filter=lfs diff=lfs merge=lfs -text
+*.sam filter=lfs diff=lfs merge=lfs -text
+*.raw filter=lfs diff=lfs merge=lfs -text
+# Audio files - compressed
+*.aac filter=lfs diff=lfs merge=lfs -text
+*.flac filter=lfs diff=lfs merge=lfs -text
+*.mp3 filter=lfs diff=lfs merge=lfs -text
+*.ogg filter=lfs diff=lfs merge=lfs -text
+*.wav filter=lfs diff=lfs merge=lfs -text
+# Image files - uncompressed
+*.bmp filter=lfs diff=lfs merge=lfs -text
+*.gif filter=lfs diff=lfs merge=lfs -text
+*.png filter=lfs diff=lfs merge=lfs -text
+*.tiff filter=lfs diff=lfs merge=lfs -text
+# Image files - compressed
+*.jpg filter=lfs diff=lfs merge=lfs -text
+*.jpeg filter=lfs diff=lfs merge=lfs -text
+*.webp filter=lfs diff=lfs merge=lfs -text
+# Video files - compressed
+*.mp4 filter=lfs diff=lfs merge=lfs -text
+*.webm filter=lfs diff=lfs merge=lfs -text
diff --git a/csharp/BrowserTool/.gitignore b/csharp/BrowserTool/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..31e08bafd9140be2e63cb1bb381cc3ec9c7fba05
--- /dev/null
+++ b/csharp/BrowserTool/.gitignore
@@ -0,0 +1,7 @@
+**/bin/
+**/obj/
+**/node_modules/
+**/packages/
+.vs
+**/.vs/
+.vs/
diff --git a/csharp/BrowserTool/BrowserTool.sln b/csharp/BrowserTool/BrowserTool.sln
new file mode 100644
index 0000000000000000000000000000000000000000..31a8e83978260331dea1b9e4b93d29ec97f86a27
--- /dev/null
+++ b/csharp/BrowserTool/BrowserTool.sln
@@ -0,0 +1,22 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio Version 17
+VisualStudioVersion = 17.12.35527.113
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BrowserTool", "BrowserTool\BrowserTool.csproj", "{D3A2273B-2DA3-4C63-9B54-DF3702B3D432}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug|Any CPU = Debug|Any CPU
+ Release|Any CPU = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {D3A2273B-2DA3-4C63-9B54-DF3702B3D432}.Debug|Any CPU.ActiveCfg = Debug|x64
+ {D3A2273B-2DA3-4C63-9B54-DF3702B3D432}.Debug|Any CPU.Build.0 = Debug|x64
+ {D3A2273B-2DA3-4C63-9B54-DF3702B3D432}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {D3A2273B-2DA3-4C63-9B54-DF3702B3D432}.Release|Any CPU.Build.0 = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+EndGlobal
diff --git a/csharp/BrowserTool/BrowserTool/App.config b/csharp/BrowserTool/BrowserTool/App.config
new file mode 100644
index 0000000000000000000000000000000000000000..c01eb64d96338fcb0b004b1aff2fd11072e8d11f
--- /dev/null
+++ b/csharp/BrowserTool/BrowserTool/App.config
@@ -0,0 +1,28 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/csharp/BrowserTool/BrowserTool/App.xaml b/csharp/BrowserTool/BrowserTool/App.xaml
new file mode 100644
index 0000000000000000000000000000000000000000..d917afffe88c5af2828f14a3213fc308a4fd3927
--- /dev/null
+++ b/csharp/BrowserTool/BrowserTool/App.xaml
@@ -0,0 +1,49 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/csharp/BrowserTool/BrowserTool/App.xaml.cs b/csharp/BrowserTool/BrowserTool/App.xaml.cs
new file mode 100644
index 0000000000000000000000000000000000000000..f9b806f2c8c84052360c9aeed500ff3963c66626
--- /dev/null
+++ b/csharp/BrowserTool/BrowserTool/App.xaml.cs
@@ -0,0 +1,792 @@
+using System;
+using System.Diagnostics;
+using System.Drawing;
+using System.IO;
+using System.IO.Pipes;
+using System.Reflection;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Windows;
+using CefSharp;
+using Hardcodet.Wpf.TaskbarNotification;
+using System.Runtime.InteropServices;
+using BrowserTool.Database;
+using BrowserTool.Utils;
+using System.Windows.Controls;
+using CefSharp.Wpf;
+using FontStyle = System.Drawing.FontStyle;
+using NLog;
+using NLog.Config;
+using NLog.Targets;
+
+namespace BrowserTool
+{
+ ///
+ /// App.xaml 的交互逻辑,提供应用程序的生命周期管理和单例模式支持
+ ///
+ public partial class App : Application
+ {
+ #region 常量定义
+
+ private const string MUTEX_NAME = "BrowserTool_SingleInstance";
+ private const string PIPE_NAME = "BrowserToolUrlPipe";
+ private const string WINDOW_MESSAGE_NAME = "BrowserTool_ShowMainWindow";
+
+ #endregion
+
+ #region Win32 API 导入
+
+ [DllImport("user32.dll", SetLastError = true)]
+ private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
+
+ [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
+ private static extern int RegisterWindowMessage(string lpString);
+
+ [DllImport("user32.dll")]
+ private static extern bool SetForegroundWindow(IntPtr hWnd);
+
+ [DllImport("user32.dll")]
+ private static extern bool IsIconic(IntPtr hWnd);
+
+ [DllImport("user32.dll")]
+ private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
+
+ [DllImport("user32.dll")]
+ private static extern bool PostMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
+
+ #endregion
+
+ #region 字段和属性
+
+ ///
+ /// CEF初始化锁对象
+ ///
+ private static readonly object _cefInitLock = new();
+
+ ///
+ /// 主窗口实例
+ ///
+ private MainWindow _mainWindow;
+
+ ///
+ /// 单例应用程序互斥锁
+ ///
+ private static readonly Mutex _mutex = new(true, MUTEX_NAME);
+
+ ///
+ /// 是否拥有互斥锁
+ ///
+ private static bool _mutexOwned;
+
+ ///
+ /// 命名管道服务器线程
+ ///
+ private Thread _pipeServerThread;
+
+ ///
+ /// 命名管道服务器取消令牌源
+ ///
+ private CancellationTokenSource _pipeServerCancellation;
+
+ ///
+ /// 鼠标活动模拟器
+ ///
+ private static MouseActivitySimulator _mouseActivitySimulator;
+
+ ///
+ /// 自动签到模拟器
+ ///
+ private static AutoCheckInSimulator _checkInSimulator;
+
+ ///
+ /// 自定义窗口消息ID
+ ///
+ private static readonly int WM_SHOWMAINWINDOW_CUSTOM = RegisterWindowMessage(WINDOW_MESSAGE_NAME);
+
+ ///
+ /// 日志记录器
+ ///
+ private static readonly Logger _logger = LogManager.GetCurrentClassLogger();
+
+ #endregion
+
+ #region 托盘菜单事件处理
+
+ ///
+ /// 处理设置菜单点击事件
+ ///
+ /// 事件发送者
+ /// 事件参数
+ private void TrayMenu_Settings_Click(object sender, RoutedEventArgs e)
+ {
+ if (!LoginManager.IsLoggedIn) return;
+
+ try
+ {
+ var settingsWindow = new SettingsWindow
+ {
+ Owner = _mainWindow
+ };
+ settingsWindow.ShowDialog();
+ }
+ catch (Exception ex)
+ {
+ LogError("打开设置窗口时发生错误", ex);
+ ShowErrorMessage("无法打开设置窗口,请重试。");
+ }
+ }
+
+ ///
+ /// 处理退出菜单点击事件
+ ///
+ /// 事件发送者
+ /// 事件参数
+ private void TrayMenu_Exit_Click(object sender, RoutedEventArgs e) => Shutdown();
+
+ ///
+ /// 处理修改密码菜单点击事件
+ ///
+ /// 事件发送者
+ /// 事件参数
+ private void TrayMenu_ChangePassword_Click(object sender, RoutedEventArgs e)
+ {
+ if (!Utils.LoginManager.IsLoggedIn) return;
+
+ try
+ {
+ var changePasswordWindow = new ChangePasswordWindow
+ {
+ Owner = _mainWindow
+ };
+ changePasswordWindow.ShowDialog();
+ }
+ catch (Exception ex)
+ {
+ LogError("打开修改密码窗口时发生错误", ex);
+ ShowErrorMessage("无法打开修改密码窗口,请重试。");
+ }
+ }
+
+ ///
+ /// 处理显示主窗口菜单点击事件
+ ///
+ /// 事件发送者
+ /// 事件参数
+ private void TrayMenu_Show_Click(object sender, RoutedEventArgs e)
+ {
+ if (Utils.LoginManager.IsLoggedIn)
+ {
+ ShowMainWindow();
+ }
+ }
+
+ ///
+ /// 处理托盘图标双击事件
+ ///
+ /// 事件发送者
+ /// 事件参数
+ private void TrayIcon_TrayMouseDoubleClick(object sender, RoutedEventArgs e) => ShowMainWindow();
+
+ #endregion
+
+ #region 公共方法
+
+ ///
+ /// 显示主窗口并激活
+ ///
+ public void ShowMainWindow()
+ {
+ if (_mainWindow == null) return;
+
+ try
+ {
+ _mainWindow.Show();
+ _mainWindow.WindowState = WindowState.Normal;
+ _mainWindow.Activate();
+
+ // 确保窗口在最前面,然后取消置顶
+ _mainWindow.Topmost = true;
+ _mainWindow.Topmost = false;
+ }
+ catch (Exception ex)
+ {
+ LogError("显示主窗口时发生错误", ex);
+ }
+ }
+
+ ///
+ /// 获取当前应用程序实例
+ ///
+ /// 当前应用程序实例
+ public static App GetCurrentApp() => Current as App;
+
+ ///
+ /// 获取AutoCheckInSimulator实例
+ ///
+ /// AutoCheckInSimulator实例
+ public static AutoCheckInSimulator GetAutoCheckInSimulator() => _checkInSimulator;
+
+ #endregion
+
+ #region 私有方法
+
+ ///
+ /// 初始化CEF浏览器引擎
+ ///
+ /// CEF初始化失败时抛出
+ private void InitializeCef()
+ {
+ if (Cef.IsInitialized == true) return;
+
+ lock (_cefInitLock)
+ {
+ if (Cef.IsInitialized == true) return;
+
+ try
+ {
+ var settings = CreateCefSettings();
+ Cef.Initialize(settings);
+ }
+ catch (Exception ex)
+ {
+ LogError("CEF初始化失败", ex);
+ ShowErrorMessage($"浏览器引擎初始化失败: {ex.Message}");
+ throw new InvalidOperationException("CEF初始化失败", ex);
+ }
+ }
+ }
+
+ ///
+ /// 创建CEF设置配置
+ ///
+ /// 配置好的CEF设置
+ private static CefSettings CreateCefSettings()
+ {
+ var settings = new CefSettings();
+ string exePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
+ ?? throw new InvalidOperationException("无法获取应用程序路径");
+
+ // 设置缓存路径
+ string cachePath = Path.Combine(exePath, "CEF");
+ Directory.CreateDirectory(cachePath);
+ settings.CachePath = cachePath;
+
+ // 设置日志文件路径
+ string logPath = Path.Combine(exePath, @"CEF\Log");
+ Directory.CreateDirectory(logPath);
+ settings.LogFile = Path.Combine(logPath, "cef.log");
+
+ // 基本设置
+ settings.Locale = "zh-CN";
+ settings.PersistSessionCookies = true;
+
+ // 性能优化设置
+ ConfigureCefPerformance(settings);
+
+ return settings;
+ }
+
+ ///
+ /// 配置CEF性能优化参数
+ ///
+ /// CEF设置对象
+ private static void ConfigureCefPerformance(CefSettings settings)
+ {
+ var args = settings.CefCommandLineArgs;
+
+ // 启用硬件加速
+ args.Add("enable-gpu", "1");
+ args.Add("enable-gpu-compositing", "1");
+ args.Add("enable-gpu-rasterization", "1");
+
+ // 内存优化
+ args.Add("disable-gpu-shader-disk-cache", "1");
+ args.Add("renderer-process-limit", "1");
+ args.Add("disable-extensions", "1");
+ args.Add("disable-component-update", "1");
+ }
+
+ ///
+ /// 根据登录状态更新托盘菜单
+ ///
+ /// 是否已登录
+ private void UpdateTrayMenuState(bool isLoggedIn)
+ {
+ try
+ {
+ if (Current.Resources["TrayIcon"] is not TaskbarIcon trayIcon ||
+ trayIcon.ContextMenu?.Items == null) return;
+
+ foreach (var item in trayIcon.ContextMenu.Items)
+ {
+ if (item is not MenuItem menuItem) continue;
+
+ switch (menuItem.Header?.ToString())
+ {
+ case "设置":
+ UpdateMenuItem(menuItem, isLoggedIn, "请先登录后再使用设置功能");
+ break;
+ case "修改密码":
+ UpdateMenuItem(menuItem, isLoggedIn, "请先登录后再修改密码");
+ break;
+ }
+ }
+
+ Debug.WriteLine($"[托盘菜单状态更新] 登录状态: {isLoggedIn}");
+ }
+ catch (Exception ex)
+ {
+ LogError("更新托盘菜单状态时发生错误", ex);
+ }
+ }
+
+ ///
+ /// 更新菜单项状态
+ ///
+ /// 菜单项
+ /// 是否启用
+ /// 禁用时的提示文本
+ private static void UpdateMenuItem(MenuItem menuItem, bool isEnabled, string disabledTooltip)
+ {
+ menuItem.IsEnabled = isEnabled;
+ menuItem.ToolTip = isEnabled ? null : disabledTooltip;
+ }
+
+ ///
+ /// 启动命名管道服务器,用于接收其他实例发送的URL
+ ///
+ private void StartPipeServer()
+ {
+ _pipeServerCancellation = new CancellationTokenSource();
+ var cancellationToken = _pipeServerCancellation.Token;
+
+ _pipeServerThread = new Thread(() => RunPipeServer(cancellationToken))
+ {
+ IsBackground = true,
+ Name = "PipeServerThread"
+ };
+ _pipeServerThread.Start();
+ }
+
+ ///
+ /// 运行命名管道服务器循环
+ ///
+ /// 取消令牌
+ private void RunPipeServer(CancellationToken cancellationToken)
+ {
+ while (!cancellationToken.IsCancellationRequested)
+ {
+ try
+ {
+ using var pipeServer = new NamedPipeServerStream(PIPE_NAME, PipeDirection.In);
+
+ // 使用异步等待连接,支持取消
+ var connectTask = Task.Run(() => pipeServer.WaitForConnection(), cancellationToken);
+ connectTask.Wait(cancellationToken);
+
+ using var reader = new StreamReader(pipeServer, Encoding.UTF8);
+ string url = reader.ReadLine();
+
+ if (!string.IsNullOrWhiteSpace(url))
+ {
+ ProcessReceivedUrl(url);
+ }
+ }
+ catch (OperationCanceledException)
+ {
+ // 正常取消,退出循环
+ break;
+ }
+ catch (Exception ex)
+ {
+ LogError("命名管道服务器运行时发生错误", ex);
+
+ // 发生错误时短暂延迟后重试
+ if (!cancellationToken.IsCancellationRequested)
+ {
+ Thread.Sleep(1000);
+ }
+ }
+ }
+ }
+
+ ///
+ /// 处理从命名管道接收到的URL
+ ///
+ /// 接收到的URL
+ private void ProcessReceivedUrl(string url)
+ {
+ try
+ {
+ Dispatcher.BeginInvoke(new Action(() =>
+ {
+ if (_mainWindow != null && Utils.LoginManager.IsLoggedIn)
+ {
+ _mainWindow.OpenUrlInTab("Loading...", url, false);
+ ShowMainWindow();
+ }
+ }));
+ }
+ catch (Exception ex)
+ {
+ LogError("处理接收到的URL时发生错误", ex);
+ }
+ }
+
+ ///
+ /// 通过命名管道发送URL到主实例
+ ///
+ /// 要发送的URL
+ /// 是否发送成功
+ private static bool SendUrlToPipe(string url)
+ {
+ try
+ {
+ using var pipeClient = new NamedPipeClientStream(".", PIPE_NAME, PipeDirection.Out);
+ pipeClient.Connect(1000); // 1秒超时
+
+ using var writer = new StreamWriter(pipeClient, Encoding.UTF8);
+ writer.WriteLine(url);
+ writer.Flush();
+
+ return true;
+ }
+ catch (Exception ex)
+ {
+ Debug.WriteLine($"[发送URL到管道失败] {ex.Message}");
+ return false;
+ }
+ }
+
+ ///
+ /// 初始化托盘图标
+ ///
+ /// 是否初始化成功
+ private bool InitializeTrayIcon()
+ {
+ try
+ {
+ if (Current.Resources["TrayIcon"] is not TaskbarIcon trayIcon) return false;
+
+ var iconStream = GetResourceStream(new Uri("pack://application:,,,/Resources/app.ico"))?.Stream;
+ if (iconStream != null)
+ {
+ trayIcon.Icon = new Icon(iconStream);
+ }
+
+ trayIcon.TrayMouseDoubleClick += TrayIcon_TrayMouseDoubleClick;
+ return true;
+ }
+ catch (Exception ex)
+ {
+ LogError("初始化托盘图标时发生错误", ex);
+ return false;
+ }
+ }
+
+ ///
+ /// 处理命令行参数中的URL
+ ///
+ /// 命令行参数
+ private void ProcessCommandLineUrl(string[] args)
+ {
+ if (args?.Length == 0) return;
+
+ string url = args[0];
+ if (string.IsNullOrWhiteSpace(url) || !IsValidUrl(url)) return;
+
+ try
+ {
+ _mainWindow?.Dispatcher.Invoke(() =>
+ {
+ _mainWindow.OpenUrlInTab("Loading...", url, false);
+ });
+ }
+ catch (Exception ex)
+ {
+ LogError("处理命令行URL时发生错误", ex);
+ }
+ }
+
+ ///
+ /// 验证URL格式是否有效
+ ///
+ /// 要验证的URL
+ /// 是否为有效URL
+ private static bool IsValidUrl(string url) =>
+ url.StartsWith("http://", StringComparison.OrdinalIgnoreCase) ||
+ url.StartsWith("https://", StringComparison.OrdinalIgnoreCase) ||
+ url.StartsWith("file://", StringComparison.OrdinalIgnoreCase);
+
+ ///
+ /// 显示登录窗口并处理登录结果
+ ///
+ /// 是否登录成功
+ private bool ShowLoginWindow()
+ {
+ try
+ {
+ var loginWindow = new LoginWindow();
+ if (loginWindow.ShowDialog() != true) return false;
+
+ // 设置登录状态并订阅状态变化事件
+ Utils.LoginManager.SetLoggedIn();
+ Utils.LoginManager.OnLoginStatusChanged += UpdateTrayMenuState;
+
+ // 初始化托盘菜单状态
+ UpdateTrayMenuState(true);
+
+ return true;
+ }
+ catch (Exception ex)
+ {
+ LogError("显示登录窗口时发生错误", ex);
+ ShowErrorMessage("登录窗口初始化失败,程序即将退出。");
+ return false;
+ }
+ }
+
+ ///
+ /// 记录错误日志
+ ///
+ /// 错误消息
+ /// 异常对象
+ private static void LogError(string message, Exception exception)
+ {
+ _logger.Error($"[错误] {message}:", exception);
+ }
+
+ ///
+ /// 显示错误消息框
+ ///
+ /// 错误消息
+ private static void ShowErrorMessage(string message)
+ {
+ MessageBox.Show(message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
+ }
+
+ #endregion
+
+ #region 应用程序生命周期
+
+ ///
+ /// 应用程序启动时的处理逻辑
+ ///
+ /// 启动事件参数
+ protected override void OnStartup(StartupEventArgs e)
+ {
+ base.OnStartup(e);
+
+ try
+ {
+ // 初始化模拟器
+ InitializeSimulators();
+
+ // 检查单例应用程序
+ if (!CheckSingleInstance(e)) return;
+
+ // 初始化应用程序核心组件
+ if (!InitializeApplication(e)) return;
+
+ // 显示登录窗口并处理结果
+ if (ShowLoginWindow())
+ {
+ ShowMainWindowAndActivate();
+ }
+ else
+ {
+ Shutdown();
+ }
+ }
+ catch (Exception ex)
+ {
+ MessageBox.Show($"应用程序启动失败: {ex.Message}\n{ex.StackTrace}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
+ }
+ }
+
+ ///
+ /// 初始化模拟器组件
+ ///
+ private static void InitializeSimulators()
+ {
+ _checkInSimulator = new AutoCheckInSimulator();
+ _checkInSimulator.Start();
+
+ _mouseActivitySimulator = new MouseActivitySimulator();
+ _mouseActivitySimulator.Start();
+ }
+
+ ///
+ /// 检查单例应用程序实例
+ ///
+ /// 启动参数
+ /// 是否应该继续启动
+ private bool CheckSingleInstance(StartupEventArgs e)
+ {
+ if (_mutex.WaitOne(TimeSpan.Zero, false))
+ {
+ _mutexOwned = true;
+ StartPipeServer();
+ return true;
+ }
+
+ // 已有实例在运行,发送URL到主实例
+ HandleExistingInstance(e.Args);
+ return false;
+ }
+
+ ///
+ /// 处理已存在实例的情况
+ ///
+ /// 命令行参数
+ private void HandleExistingInstance(string[] args)
+ {
+ // 发送URL到主实例
+ if (args?.Length > 0)
+ {
+ string url = args[0];
+ if (IsValidUrl(url))
+ {
+ SendUrlToPipe(url);
+ }
+ }
+
+ // 激活已存在的窗口
+ IntPtr hWnd = FindWindow(null, "Browser Tool");
+ if (hWnd != IntPtr.Zero)
+ {
+ PostMessage(hWnd, WM_SHOWMAINWINDOW_CUSTOM, IntPtr.Zero, IntPtr.Zero);
+ }
+
+ Shutdown();
+ }
+
+ ///
+ /// 初始化应用程序核心组件
+ ///
+ /// 启动参数
+ /// 是否初始化成功
+ private bool InitializeApplication(StartupEventArgs e)
+ {
+ try
+ {
+ // 初始化CEF
+ InitializeCef();
+
+ // 初始化数据库
+ //DatabaseInitializer.Initialize();
+
+ // 初始化托盘图标
+ if (!InitializeTrayIcon()) return false;
+
+ // 创建主窗口
+ CreateMainWindow(e.Args);
+
+ return true;
+ }
+ catch (Exception ex)
+ {
+ LogError("初始化应用程序组件时发生错误", ex);
+ return false;
+ }
+ }
+
+ ///
+ /// 创建并配置主窗口
+ ///
+ /// 命令行参数
+ private void CreateMainWindow(string[] args)
+ {
+ _mainWindow = new MainWindow();
+ MainWindow = _mainWindow;
+
+ // 处理命令行参数
+ ProcessCommandLineUrl(args);
+
+ // 监听主窗口关闭事件
+ _mainWindow.Closing += (_, e) =>
+ {
+ e.Cancel = true;
+ _mainWindow.Hide();
+ };
+ }
+
+ ///
+ /// 显示并激活主窗口
+ ///
+ private void ShowMainWindowAndActivate()
+ {
+ _mainWindow.Show();
+ _mainWindow.WindowState = WindowState.Normal;
+ _mainWindow.Activate();
+ }
+
+ ///
+ /// 应用程序退出时的清理逻辑
+ ///
+ /// 退出事件参数
+ protected override void OnExit(ExitEventArgs e)
+ {
+ try
+ {
+ CleanupResources();
+ }
+ catch (Exception ex)
+ {
+ LogError("应用程序退出清理时发生错误", ex);
+ }
+ finally
+ {
+ base.OnExit(e);
+ }
+ }
+
+ ///
+ /// 清理应用程序资源
+ ///
+ private void CleanupResources()
+ {
+ // 释放互斥锁
+ if (_mutexOwned)
+ {
+ _mutex.ReleaseMutex();
+ _mutexOwned = false;
+ }
+
+ // 停止模拟器
+ _checkInSimulator?.Stop();
+ _mouseActivitySimulator?.Stop();
+
+ // 停止命名管道服务器
+ _pipeServerCancellation?.Cancel();
+ _pipeServerThread?.Join(TimeSpan.FromSeconds(2));
+
+ // 清理浏览器相关资源
+ CleanupBrowserResources();
+ }
+
+ ///
+ /// 清理浏览器相关资源
+ ///
+ private static void CleanupBrowserResources()
+ {
+ try
+ {
+ Browser.BrowserInstanceManager.Instance?.CleanupAllBrowsers();
+ ImageCache.ClearCache();
+
+ if (Cef.IsInitialized == true)
+ {
+ Cef.Shutdown();
+ }
+ }
+ catch (Exception ex)
+ {
+ Debug.WriteLine($"清理浏览器资源时发生错误: {ex.Message}");
+ }
+ }
+
+ #endregion
+ }
+}
\ No newline at end of file
diff --git a/csharp/BrowserTool/BrowserTool/Browser/BrowserInstanceManager.cs b/csharp/BrowserTool/BrowserTool/Browser/BrowserInstanceManager.cs
new file mode 100644
index 0000000000000000000000000000000000000000..6d56803fa52e5ef03f756ab9aea85cdad77ace9e
--- /dev/null
+++ b/csharp/BrowserTool/BrowserTool/Browser/BrowserInstanceManager.cs
@@ -0,0 +1,214 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Windows;
+using CefSharp;
+using CefSharp.Wpf;
+
+namespace BrowserTool.Browser
+{
+ ///
+ /// 浏览器实例管理器,负责创建和管理浏览器实例
+ /// 采用无缓存策略,确保每个标签页都是全新、干净的环境
+ ///
+ public class BrowserInstanceManager
+ {
+ private static BrowserInstanceManager _instance;
+ private readonly Dictionary _activeBrowsers = new Dictionary();
+
+ // 单例模式
+ public static BrowserInstanceManager Instance => _instance ??= new BrowserInstanceManager();
+
+ private BrowserInstanceManager()
+ {
+ // 私有构造函数,确保单例
+ }
+
+ ///
+ /// 创建一个新的浏览器实例
+ ///
+ /// 要加载的URL(可为空,由调用方控制加载时机)
+ /// 标签页ID
+ /// 浏览器实例
+ public ChromiumWebBrowser GetBrowser(string url, string tabId)
+ {
+ lock (_activeBrowsers)
+ {
+ // 如果该标签页已有浏览器实例,先清理
+ if (_activeBrowsers.ContainsKey(tabId))
+ {
+ System.Diagnostics.Debug.WriteLine($"[BrowserInstanceManager] 标签页已存在浏览器实例,先清理 - TabId: {tabId}");
+ ReleaseBrowser(tabId, dispose: true);
+ }
+
+ // 总是创建全新的浏览器实例
+ var browser = new ChromiumWebBrowser();
+
+ // 设置通用处理程序
+ browser.DownloadHandler = new CefDownloadHandler();
+ browser.MenuHandler = new CefMenuHandler();
+ browser.LifeSpanHandler = new CefLifeSpanHandler();
+
+ // 添加页面加载完成事件,注入深色滚动条样式
+ browser.FrameLoadEnd += (sender, args) => {
+ if (args.Frame.IsMain)
+ {
+ // 注入深色滚动条样式
+ DarkThemeStyleInjector.InjectDarkThemeStyles(args.Frame);
+ }
+ };
+
+ // 注册到活动浏览器列表
+ _activeBrowsers[tabId] = browser;
+
+ System.Diagnostics.Debug.WriteLine($"[BrowserInstanceManager] 创建新浏览器实例 - TabId: {tabId}");
+
+ // 只有在URL不为空且浏览器已初始化时才加载URL
+ if (!string.IsNullOrEmpty(url) && browser.IsBrowserInitialized)
+ {
+ browser.LoadUrl(url);
+ System.Diagnostics.Debug.WriteLine($"[BrowserInstanceManager] 直接加载URL: {url}");
+ }
+ else if (!string.IsNullOrEmpty(url))
+ {
+ // 如果浏览器未初始化,等待初始化完成后加载
+ DependencyPropertyChangedEventHandler browserInitializedHandler = null;
+ browserInitializedHandler = (sender, e) =>
+ {
+ try
+ {
+ if (browser.IsBrowserInitialized)
+ {
+ browser.IsBrowserInitializedChanged -= browserInitializedHandler;
+ browser.LoadUrl(url);
+ System.Diagnostics.Debug.WriteLine($"[BrowserInstanceManager] 浏览器初始化完成后加载URL: {url}");
+ }
+ }
+ catch (Exception ex)
+ {
+ System.Diagnostics.Debug.WriteLine($"[BrowserInstanceManager] 延迟加载URL时发生异常: {ex.Message}");
+ }
+ };
+ browser.IsBrowserInitializedChanged += browserInitializedHandler;
+ }
+
+ return browser;
+ }
+ }
+
+ ///
+ /// 释放并销毁浏览器实例
+ ///
+ /// 标签页ID
+ /// 是否销毁实例(默认为true,确保完全清理)
+ public void ReleaseBrowser(string tabId, bool dispose = true)
+ {
+ if (string.IsNullOrEmpty(tabId))
+ {
+ System.Diagnostics.Debug.WriteLine("[BrowserInstanceManager] ReleaseBrowser: tabId为空");
+ return;
+ }
+
+ lock (_activeBrowsers)
+ {
+ if (_activeBrowsers.TryGetValue(tabId, out ChromiumWebBrowser browser))
+ {
+ _activeBrowsers.Remove(tabId);
+ System.Diagnostics.Debug.WriteLine($"[BrowserInstanceManager] 释放浏览器实例 - TabId: {tabId}");
+
+ // 总是销毁实例,确保完全清理
+ DisposeBrowserInstance(browser, tabId);
+ }
+ else
+ {
+ System.Diagnostics.Debug.WriteLine($"[BrowserInstanceManager] 未找到要释放的浏览器实例 - TabId: {tabId}");
+ }
+ }
+ }
+
+ ///
+ /// 安全地销毁浏览器实例
+ ///
+ /// 浏览器实例
+ /// 标签页ID
+ private void DisposeBrowserInstance(ChromiumWebBrowser browser, string tabId)
+ {
+ try
+ {
+ if (browser != null && !browser.IsDisposed)
+ {
+ // 清理事件处理器
+ CleanupBrowserEventHandlers(browser);
+
+ // 销毁浏览器实例
+ browser.Dispose();
+ System.Diagnostics.Debug.WriteLine($"[BrowserInstanceManager] 浏览器实例已销毁 - TabId: {tabId}");
+ }
+ }
+ catch (Exception ex)
+ {
+ System.Diagnostics.Debug.WriteLine($"[BrowserInstanceManager] 销毁浏览器实例时发生异常 - TabId: {tabId}, Error: {ex.Message}");
+ }
+ }
+
+ ///
+ /// 清理浏览器事件处理器
+ ///
+ /// 浏览器实例
+ private void CleanupBrowserEventHandlers(ChromiumWebBrowser browser)
+ {
+ try
+ {
+ if (browser?.Tag is Dictionary browserTags)
+ {
+ // 清理存储在Tag中的事件处理器引用
+ if (browserTags.TryGetValue("titleUpdateHandler", out object titleHandler) &&
+ titleHandler is EventHandler titleUpdateHandler)
+ {
+ browser.FrameLoadEnd -= titleUpdateHandler;
+ }
+
+ if (browserTags.TryGetValue("loadingStateChangedHandler", out object loadingHandler) &&
+ loadingHandler is EventHandler loadingStateChangedHandler)
+ {
+ browser.LoadingStateChanged -= loadingStateChangedHandler;
+ }
+
+ browserTags.Clear();
+ browser.Tag = null;
+
+ System.Diagnostics.Debug.WriteLine("[BrowserInstanceManager] 浏览器事件处理器已清理");
+ }
+ }
+ catch (Exception ex)
+ {
+ System.Diagnostics.Debug.WriteLine($"[BrowserInstanceManager] 清理事件处理器时发生异常: {ex.Message}");
+ }
+ }
+
+ ///
+ /// 清理所有浏览器实例
+ ///
+ public void CleanupAllBrowsers()
+ {
+ lock (_activeBrowsers)
+ {
+ // 清理所有活动的浏览器实例
+ foreach (var kvp in _activeBrowsers.ToList())
+ {
+ try
+ {
+ DisposeBrowserInstance(kvp.Value, kvp.Key);
+ }
+ catch (Exception ex)
+ {
+ System.Diagnostics.Debug.WriteLine($"[BrowserInstanceManager] 清理浏览器实例时发生异常 - TabId: {kvp.Key}, Error: {ex.Message}");
+ }
+ }
+ _activeBrowsers.Clear();
+
+ System.Diagnostics.Debug.WriteLine("[BrowserInstanceManager] 所有浏览器实例已清理");
+ }
+ }
+ }
+}
diff --git a/csharp/BrowserTool/BrowserTool/Browser/BrowserTabManager.cs b/csharp/BrowserTool/BrowserTool/Browser/BrowserTabManager.cs
new file mode 100644
index 0000000000000000000000000000000000000000..5d88b3563c68117b58e8ba962d6fc48d521f821b
--- /dev/null
+++ b/csharp/BrowserTool/BrowserTool/Browser/BrowserTabManager.cs
@@ -0,0 +1,79 @@
+using System.Windows.Controls;
+using CefSharp;
+using CefSharp.Wpf;
+
+namespace BrowserTool.Browser
+{
+ ///
+ /// 浏览器Tab管理器,负责Tab的添加、关闭等操作
+ ///
+ public class BrowserTabManager
+ {
+ private TabControl _tabControl;
+ private MainWindow _mainWindow;
+
+ public BrowserTabManager(TabControl tabControl, MainWindow mainWindow)
+ {
+ _tabControl = tabControl;
+ _mainWindow = mainWindow;
+ }
+
+ ///
+ /// 添加新Tab
+ ///
+ public TabItem AddTab(string header, object content)
+ {
+ var tabItem = new TabItem();
+ var customHeader = new CustomTabItem();
+ customHeader.Content = header;
+ tabItem.Header = customHeader;
+ tabItem.Content = content;
+
+ // 设置浏览器事件处理
+ var chromiumBrowser = content as ChromiumWebBrowser;
+ if (chromiumBrowser != null)
+ {
+ var headerControl = tabItem.Header as CustomTabItem;
+ chromiumBrowser.TitleChanged += (s, e) =>
+ {
+ if (headerControl != null)
+ {
+ headerControl.Content = e.NewValue;
+ }
+ };
+
+ chromiumBrowser.AddressChanged += (s, e) =>
+ {
+ if (tabItem == _tabControl.SelectedItem)
+ {
+ var contentPresenter = tabItem.Content as ContentPresenter;
+ if (contentPresenter != null)
+ {
+ var grid = contentPresenter.Content as Grid;
+ if (grid != null)
+ {
+ var urlTextBox = grid.FindName("UrlTextBox") as TextBox;
+ if (urlTextBox != null)
+ {
+ urlTextBox.Text = chromiumBrowser.Address;
+ }
+ }
+ }
+ }
+ };
+ }
+
+ _tabControl.Items.Add(tabItem);
+ _tabControl.SelectedItem = tabItem;
+ return tabItem;
+ }
+
+ ///
+ /// 关闭指定Tab
+ ///
+ public void CloseTab(TabItem tabItem)
+ {
+ _tabControl.Items.Remove(tabItem);
+ }
+ }
+}
\ No newline at end of file
diff --git a/csharp/BrowserTool/BrowserTool/Browser/CefDownloadHandler.cs b/csharp/BrowserTool/BrowserTool/Browser/CefDownloadHandler.cs
new file mode 100644
index 0000000000000000000000000000000000000000..33b7418dcd14de9e4587dedea83750b9e5ff9ac3
--- /dev/null
+++ b/csharp/BrowserTool/BrowserTool/Browser/CefDownloadHandler.cs
@@ -0,0 +1,69 @@
+using CefSharp;
+using System;
+using System.Windows;
+
+namespace BrowserTool.Browser
+{
+ ///
+ /// CefSharp下载处理器,支持文件下载
+ ///
+ public class CefDownloadHandler : IDownloadHandler
+ {
+ public event Action OnBeforeDownloadFired;
+ public event Action OnDownloadUpdatedFired;
+
+ public bool OnBeforeDownload(IWebBrowser browserControl, IBrowser browser, DownloadItem downloadItem, IBeforeDownloadCallback callback)
+ {
+ // 下载前回调,可自定义保存路径
+ Application.Current.Dispatcher.Invoke(() =>
+ {
+ OnBeforeDownloadFired?.Invoke(downloadItem.SuggestedFileName);
+ // 新建或更新下载任务
+ DownloadManager.Instance.AddOrUpdateTask(new DownloadTask
+ {
+ FileName = downloadItem.SuggestedFileName,
+ FullPath = downloadItem.FullPath,
+ ReceivedBytes = downloadItem.ReceivedBytes,
+ TotalBytes = downloadItem.TotalBytes,
+ IsComplete = false,
+ Status = "正在下载"
+ });
+ });
+ if (!callback.IsDisposed)
+ {
+ // 默认保存到用户下载目录
+ string path = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Downloads", downloadItem.SuggestedFileName);
+ callback.Continue(path, showDialog: true);
+ }
+ // 返回true表示下载应该继续
+ return true;
+ }
+
+ public void OnDownloadUpdated(IWebBrowser browserControl, IBrowser browser, DownloadItem downloadItem, IDownloadItemCallback callback)
+ {
+ // 下载进度更新
+ Application.Current.Dispatcher.Invoke(() =>
+ {
+ OnDownloadUpdatedFired?.Invoke(downloadItem.FullPath);
+ DownloadManager.Instance.AddOrUpdateTask(new DownloadTask
+ {
+ FileName = downloadItem.SuggestedFileName,
+ FullPath = downloadItem.FullPath,
+ ReceivedBytes = downloadItem.ReceivedBytes,
+ TotalBytes = downloadItem.TotalBytes,
+ IsComplete = downloadItem.IsComplete,
+ IsCancelled = downloadItem.IsCancelled,
+ IsError = downloadItem.IsCancelled || downloadItem.IsCancelled,
+ Status = downloadItem.IsComplete ? "已完成" : (downloadItem.IsCancelled ? "已取消" : "正在下载"),
+ Callback = callback
+ });
+ });
+ }
+
+ // 新增:实现IDownloadHandler接口的CanDownload方法,允许所有下载
+ public bool CanDownload(IWebBrowser browserControl, IBrowser browser, string url, string requestMethod)
+ {
+ return true;
+ }
+ }
+}
\ No newline at end of file
diff --git a/csharp/BrowserTool/BrowserTool/Browser/CefHelper.cs b/csharp/BrowserTool/BrowserTool/Browser/CefHelper.cs
new file mode 100644
index 0000000000000000000000000000000000000000..d338e2742947d0913d96d63a842d496dae1c3b99
--- /dev/null
+++ b/csharp/BrowserTool/BrowserTool/Browser/CefHelper.cs
@@ -0,0 +1,21 @@
+using CefSharp.Wpf;
+
+namespace BrowserTool.Browser
+{
+ ///
+ /// CefSharp浏览器辅助方法
+ ///
+ public static class CefHelper
+ {
+ ///
+ /// 打开开发者工具(F12)
+ ///
+ public static void ShowDevTools(ChromiumWebBrowser browser)
+ {
+ if (browser != null && browser.GetBrowser() != null)
+ {
+ browser.GetBrowser().GetHost().ShowDevTools();
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/csharp/BrowserTool/BrowserTool/Browser/CefLifeSpanHandler.cs b/csharp/BrowserTool/BrowserTool/Browser/CefLifeSpanHandler.cs
new file mode 100644
index 0000000000000000000000000000000000000000..75d9593811c80f1343754770e71b3c80c64647dc
--- /dev/null
+++ b/csharp/BrowserTool/BrowserTool/Browser/CefLifeSpanHandler.cs
@@ -0,0 +1,25 @@
+using CefSharp;
+using CefSharp.Wpf;
+
+namespace BrowserTool.Browser
+{
+ ///
+ /// 拦截target=_blank等新窗口请求,在当前Tab打开
+ ///
+ public class CefLifeSpanHandler : ILifeSpanHandler
+ {
+ public bool DoClose(IWebBrowser chromiumWebBrowser, IBrowser browser) => false;
+ public void OnAfterCreated(IWebBrowser chromiumWebBrowser, IBrowser browser) { }
+ public void OnBeforeClose(IWebBrowser chromiumWebBrowser, IBrowser browser) { }
+
+ public bool OnBeforePopup(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, string targetUrl,
+ string targetFrameName, WindowOpenDisposition targetDisposition, bool userGesture, IPopupFeatures popupFeatures,
+ IWindowInfo windowInfo, IBrowserSettings browserSettings, ref bool noJavascriptAccess, out IWebBrowser newBrowser)
+ {
+ newBrowser = null;
+ // 在当前Tab打开新链接
+ chromiumWebBrowser.Load(targetUrl);
+ return true; // 阻止新窗口
+ }
+ }
+}
\ No newline at end of file
diff --git a/csharp/BrowserTool/BrowserTool/Browser/CefMenuHandler.cs b/csharp/BrowserTool/BrowserTool/Browser/CefMenuHandler.cs
new file mode 100644
index 0000000000000000000000000000000000000000..7967abc12565ab58503ee59649860e4ef0cf238a
--- /dev/null
+++ b/csharp/BrowserTool/BrowserTool/Browser/CefMenuHandler.cs
@@ -0,0 +1,170 @@
+using CefSharp;
+using System;
+using System.Windows;
+using System.Windows.Controls;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Windows.Controls.Primitives;
+using BrowserTool;
+
+namespace BrowserTool.Browser
+{
+ ///
+ /// CefSharp右键菜单处理器,支持自定义菜单项
+ ///
+ public class CefMenuHandler : IContextMenuHandler
+ {
+ private const int CMD_VIEW_SOURCE = 26501;
+ private const int CMD_COPY_URL = 26502;
+ private const int CMD_DOWNLOAD_MANAGER = 26503;
+ private const int CMD_TOGGLE_URL_BAR = 26504;
+ private const int CMD_GO_TO_URL = 26505;
+ private const int CMD_GO_TO_URL_NEW_WINDOW = 26506;
+ private const int CMD_REFRESH = 26507;
+ private const int CMD_OPEN_LINK_NEW_TAB = 26508;
+ private const int CMD_COPY_SELECTION = 26509;
+
+ public void OnBeforeContextMenu(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, IMenuModel model)
+ {
+ // 清除默认菜单
+ model.Clear();
+
+ // 如果右键点击的是链接,添加"在新标签页中打开"选项
+ if (!string.IsNullOrEmpty(parameters.LinkUrl))
+ {
+ model.AddItem((CefMenuCommand)CMD_OPEN_LINK_NEW_TAB, "在新标签页中打开");
+ model.AddSeparator();
+ }
+
+ // 如果有选中的文本,添加复制选项
+ if (!string.IsNullOrEmpty(parameters.SelectionText))
+ {
+ model.AddItem((CefMenuCommand)CMD_COPY_SELECTION, "复制选中内容");
+ model.AddSeparator();
+ }
+
+ model.AddItem((CefMenuCommand)CMD_VIEW_SOURCE, "查看源代码");
+ model.AddItem((CefMenuCommand)CMD_COPY_URL, "复制网址");
+ model.AddSeparator();
+ model.AddItem((CefMenuCommand)CMD_DOWNLOAD_MANAGER, "下载管理器");
+ model.AddSeparator();
+ model.AddItem((CefMenuCommand)CMD_TOGGLE_URL_BAR, "显示/隐藏地址栏");
+ model.AddItem((CefMenuCommand)CMD_GO_TO_URL, "粘贴并访问");
+ model.AddItem((CefMenuCommand)CMD_GO_TO_URL_NEW_WINDOW, "粘贴并在新标签页中访问");
+ model.AddSeparator();
+ model.AddItem((CefMenuCommand)CMD_REFRESH, "刷新");
+ }
+
+ public bool OnContextMenuCommand(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, CefMenuCommand commandId, CefEventFlags eventFlags)
+ {
+ //粘贴并前往
+ if ((int)commandId == CMD_GO_TO_URL)
+ {
+ string clipboardText = Clipboard.GetText();
+ if (!string.IsNullOrWhiteSpace(clipboardText) && (clipboardText.StartsWith("http://") || clipboardText.StartsWith("https://")))
+ {
+ browserControl.Load(clipboardText);
+ }
+ return true;
+ }
+ //粘贴并在新标签页中访问
+ if ((int)commandId == CMD_GO_TO_URL_NEW_WINDOW)
+ {
+ string clipboardText = Clipboard.GetText();
+ if (!string.IsNullOrWhiteSpace(clipboardText) && (clipboardText.StartsWith("http://") || clipboardText.StartsWith("https://")))
+ {
+ System.Windows.Application.Current.Dispatcher.Invoke(() => {
+ var mainWindow = System.Windows.Application.Current.MainWindow as MainWindow;
+ if (mainWindow != null)
+ {
+ // 在新标签页中打开URL
+ // 直接使用 OpenUrlInTab 方法,并设置初始标题为 "Loading..."
+ // 浏览器会自动更新标题为网站标题
+ mainWindow.Dispatcher.BeginInvoke(new Action(() => {
+ // 不传入 keepOriginalTitle 参数或设置为 false,允许标题动态更新
+ mainWindow.OpenUrlInTab("Loading...", clipboardText, false);
+ }));
+ }
+ });
+ }
+ return true;
+ }
+ if ((int)commandId == CMD_OPEN_LINK_NEW_TAB)
+ {
+ // 在新标签页中打开链接
+ // 先保存LinkUrl,防止parameters对象被释放
+ string linkUrl = parameters.LinkUrl;
+ System.Windows.Application.Current.Dispatcher.Invoke(() => {
+ var mainWindow = System.Windows.Application.Current.MainWindow as MainWindow;
+ if (mainWindow != null)
+ {
+ mainWindow.Dispatcher.BeginInvoke(new Action(() => {
+ mainWindow.OpenUrlInTab("Loading...", linkUrl, false,false,0,null,false);
+ }));
+ }
+ });
+ return true;
+ }
+ if ((int)commandId == CMD_VIEW_SOURCE)
+ {
+ // 查看源代码
+ frame.ViewSource();
+ return true;
+ }
+ if ((int)commandId == CMD_COPY_URL)
+ {
+ // 复制当前URL
+ Clipboard.SetText(frame.Url);
+ return true;
+ }
+ if ((int)commandId == CMD_DOWNLOAD_MANAGER)
+ {
+ // 打开下载管理器窗口
+ System.Windows.Application.Current.Dispatcher.Invoke(() =>
+ {
+ BrowserTool.Browser.DownloadManagerWindow.ShowSingleton();
+ });
+ return true;
+ }
+ if ((int)commandId == CMD_TOGGLE_URL_BAR)
+ {
+ // 显示/隐藏地址栏
+ System.Windows.Application.Current.Dispatcher.Invoke(() =>
+ {
+ var mainWindow = System.Windows.Application.Current.MainWindow as MainWindow;
+ if (mainWindow != null)
+ {
+ mainWindow.ToggleUrlBar();
+ }
+ });
+ return true;
+ }
+ if ((int)commandId == CMD_REFRESH)
+ {
+ // 刷新页面
+ browser.Reload();
+ return true;
+ }
+ if ((int)commandId == CMD_COPY_SELECTION)
+ {
+ // 复制选中的内容
+ if (!string.IsNullOrEmpty(parameters.SelectionText))
+ {
+ Clipboard.SetText(parameters.SelectionText);
+ }
+ return true;
+ }
+ return false;
+ }
+
+ public void OnContextMenuDismissed(IWebBrowser browserControl, IBrowser browser, IFrame frame)
+ {
+ }
+
+ public bool RunContextMenu(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, IMenuModel model, IRunContextMenuCallback callback)
+ {
+ // 返回 false 使用默认菜单显示方式
+ return false;
+ }
+ }
+}
\ No newline at end of file
diff --git a/csharp/BrowserTool/BrowserTool/Browser/CustomTabItem.xaml b/csharp/BrowserTool/BrowserTool/Browser/CustomTabItem.xaml
new file mode 100644
index 0000000000000000000000000000000000000000..30e058608ac8d5fab292c0fbf9817ba3e122611f
--- /dev/null
+++ b/csharp/BrowserTool/BrowserTool/Browser/CustomTabItem.xaml
@@ -0,0 +1,39 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/csharp/BrowserTool/BrowserTool/Browser/CustomTabItem.xaml.cs b/csharp/BrowserTool/BrowserTool/Browser/CustomTabItem.xaml.cs
new file mode 100644
index 0000000000000000000000000000000000000000..ebe7f51660a06dc1b54f6880ed5369fe03820e5e
--- /dev/null
+++ b/csharp/BrowserTool/BrowserTool/Browser/CustomTabItem.xaml.cs
@@ -0,0 +1,115 @@
+using System.Windows;
+using System.Windows.Controls;
+using CefSharp;
+using CefSharp.Wpf;
+using System.Windows.Media;
+
+namespace BrowserTool.Browser
+{
+ ///
+ /// Chrome风格TabItem,带关闭按钮
+ ///
+ public partial class CustomTabItem : UserControl
+ {
+ public CustomTabItem()
+ {
+ InitializeComponent();
+ }
+
+ // 关闭按钮点击事件,触发Tab关闭
+ private void CloseButton_Click(object sender, RoutedEventArgs e)
+ {
+ // 向父级TabControl冒泡关闭事件
+ var tabItem = this.FindParent();
+ if (tabItem != null)
+ {
+ var tabControl = tabItem.FindParent();
+ if (tabControl != null)
+ {
+ tabControl.Items.Remove(tabItem);
+ }
+ }
+ }
+
+ // 复制标签页
+ private void CopyTab_Click(object sender, RoutedEventArgs e)
+ {
+ var tabItem = this.FindParent();
+ if (tabItem != null)
+ {
+ var tabControl = tabItem.FindParent();
+ if (tabControl != null)
+ {
+ // 获取当前标签页的浏览器控件
+ var browser = tabItem.Content as ChromiumWebBrowser;
+ if (browser != null)
+ {
+ // 获取当前URL
+ string currentUrl = browser.Address;
+ string currentTitle = browser.Title;
+
+ // 创建新标签页
+ var newTab = new TabItem();
+ var newBrowser = new ChromiumWebBrowser(currentUrl);
+
+ // 创建新的标题控件
+ var newHeader = new CustomTabItem();
+ newHeader.Content = GetNextTabTitle(currentTitle, tabControl);
+
+ newTab.Header = newHeader;
+ newTab.Content = newBrowser;
+
+ // 在当前标签页后插入新标签页
+ int currentIndex = tabControl.Items.IndexOf(tabItem);
+ tabControl.Items.Insert(currentIndex + 1, newTab);
+ tabControl.SelectedItem = newTab;
+ }
+ }
+ }
+ }
+
+ // 获取下一个标签页标题(自动添加数字)
+ private string GetNextTabTitle(string baseTitle, TabControl tabControl)
+ {
+ string newTitle = baseTitle;
+ int counter = 2;
+
+ // 检查是否存在相同标题的标签页
+ while (true)
+ {
+ bool exists = false;
+ foreach (TabItem item in tabControl.Items)
+ {
+ var header = item.Header as CustomTabItem;
+ if (header != null && header.Content.ToString() == newTitle)
+ {
+ exists = true;
+ break;
+ }
+ }
+
+ if (!exists)
+ break;
+
+ newTitle = $"{baseTitle} {counter}";
+ counter++;
+ }
+
+ return newTitle;
+ }
+ }
+
+ // 辅助方法:查找父级控件
+ public static class VisualTreeHelperExtensions
+ {
+ public static T FindParent(this DependencyObject child) where T : DependencyObject
+ {
+ DependencyObject parent = System.Windows.Media.VisualTreeHelper.GetParent(child);
+ while (parent != null && !(parent is T))
+ {
+ parent = System.Windows.Media.VisualTreeHelper.GetParent(parent);
+ }
+ return parent as T;
+ }
+ }
+}
\ No newline at end of file
diff --git a/csharp/BrowserTool/BrowserTool/Browser/DarkThemeStyleInjector.cs b/csharp/BrowserTool/BrowserTool/Browser/DarkThemeStyleInjector.cs
new file mode 100644
index 0000000000000000000000000000000000000000..53c6bf950f7a2b937a0468b37892b8faf90f40b3
--- /dev/null
+++ b/csharp/BrowserTool/BrowserTool/Browser/DarkThemeStyleInjector.cs
@@ -0,0 +1,77 @@
+using CefSharp;
+using System;
+using System.Text;
+
+namespace BrowserTool.Browser
+{
+ ///
+ /// 负责向CefSharp浏览器注入深色主题样式的工具类
+ ///
+ public class DarkThemeStyleInjector
+ {
+ // 深色滚动条CSS样式
+ private const string DarkScrollbarCss = @"
+ ::-webkit-scrollbar {
+ width: 12px;
+ height: 12px;
+ background-color: #2D2D30;
+ }
+
+ ::-webkit-scrollbar-track {
+ background-color: #2D2D30;
+ border-radius: 6px;
+ }
+
+ ::-webkit-scrollbar-thumb {
+ background-color: #686868;
+ border-radius: 6px;
+ }
+
+ ::-webkit-scrollbar-thumb:hover {
+ background-color: #9E9E9E;
+ }
+
+ ::-webkit-scrollbar-thumb:active {
+ background-color: #BFBFBF;
+ }
+
+ ::-webkit-scrollbar-corner {
+ background-color: #2D2D30;
+ }
+ ";
+
+ ///
+ /// 将深色主题样式注入到浏览器中
+ ///
+ /// 要注入样式的浏览器框架
+ public static void InjectDarkThemeStyles(IFrame frame)
+ {
+ if (frame == null || !frame.IsValid)
+ return;
+
+ // 创建一个JavaScript,将CSS样式注入到页面头部
+ string script = @"
+ (function() {
+ var style = document.createElement('style');
+ style.type = 'text/css';
+ style.id = 'browser-tool-dark-theme';
+ style.innerHTML = `" + DarkScrollbarCss + @"`;
+
+ // 如果已存在相同ID的样式,则先移除
+ var existingStyle = document.getElementById('browser-tool-dark-theme');
+ if (existingStyle) {
+ existingStyle.parentNode.removeChild(existingStyle);
+ }
+
+ // 将样式添加到文档头部
+ (document.head || document.documentElement).appendChild(style);
+
+ return true;
+ })();
+ ";
+
+ // 异步执行JavaScript
+ frame.ExecuteJavaScriptAsync(script);
+ }
+ }
+}
diff --git a/csharp/BrowserTool/BrowserTool/Browser/DownloadManager.cs b/csharp/BrowserTool/BrowserTool/Browser/DownloadManager.cs
new file mode 100644
index 0000000000000000000000000000000000000000..585a3ad1348d9950a5be2d58de250bee1892352b
--- /dev/null
+++ b/csharp/BrowserTool/BrowserTool/Browser/DownloadManager.cs
@@ -0,0 +1,57 @@
+using System.Collections.ObjectModel;
+using System.Linq;
+
+namespace BrowserTool.Browser
+{
+ ///
+ /// 下载任务管理器,集中管理所有下载任务(单例)
+ ///
+ public class DownloadManager
+ {
+ private static DownloadManager _instance;
+ public static DownloadManager Instance => _instance ?? (_instance = new DownloadManager());
+
+ // 下载任务列表,便于UI绑定
+ public ObservableCollection Tasks { get; } = new ObservableCollection();
+
+ ///
+ /// 添加或更新下载任务
+ ///
+ public void AddOrUpdateTask(DownloadTask task)
+ {
+ // 检查是否存在相同文件名的正在下载的任务
+ var existingTask = Tasks.FirstOrDefault(t =>
+ t.FileName == task.FileName &&
+ !t.IsComplete &&
+ !t.IsCancelled &&
+ !t.IsError);
+
+ if (existingTask == null)
+ {
+ // 如果不存在,添加新任务
+ Tasks.Add(task);
+ }
+ else
+ {
+ // 更新现有任务的进度和状态
+ existingTask.ReceivedBytes = task.ReceivedBytes;
+ existingTask.TotalBytes = task.TotalBytes;
+ existingTask.IsComplete = task.IsComplete;
+ existingTask.IsCancelled = task.IsCancelled;
+ existingTask.IsError = task.IsError;
+ existingTask.Status = task.Status;
+ }
+ }
+
+ ///
+ /// 移除任务
+ ///
+ public void RemoveTask(DownloadTask task)
+ {
+ if (Tasks.Contains(task))
+ {
+ Tasks.Remove(task);
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/csharp/BrowserTool/BrowserTool/Browser/DownloadManagerWindow.xaml b/csharp/BrowserTool/BrowserTool/Browser/DownloadManagerWindow.xaml
new file mode 100644
index 0000000000000000000000000000000000000000..60ace68819d7c0c476114b3434ca214c58252588
--- /dev/null
+++ b/csharp/BrowserTool/BrowserTool/Browser/DownloadManagerWindow.xaml
@@ -0,0 +1,41 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/csharp/BrowserTool/BrowserTool/Browser/DownloadManagerWindow.xaml.cs b/csharp/BrowserTool/BrowserTool/Browser/DownloadManagerWindow.xaml.cs
new file mode 100644
index 0000000000000000000000000000000000000000..a7a20b9287bbb74793dc0d0ef490567ab0637b90
--- /dev/null
+++ b/csharp/BrowserTool/BrowserTool/Browser/DownloadManagerWindow.xaml.cs
@@ -0,0 +1,70 @@
+using System.Diagnostics;
+using System.Windows;
+using System.Windows.Controls;
+using System.Linq;
+
+namespace BrowserTool.Browser
+{
+ ///
+ /// 下载管理器窗口,集中显示所有下载任务
+ ///
+ public partial class DownloadManagerWindow : Window
+ {
+ private static DownloadManagerWindow _instance;
+ public static void ShowSingleton()
+ {
+ if (_instance == null || !_instance.IsVisible)
+ {
+ _instance = new DownloadManagerWindow();
+ _instance.Show();
+ }
+ else
+ {
+ _instance.Activate();
+ }
+ }
+
+ public DownloadManagerWindow()
+ {
+ InitializeComponent();
+ this.DataContext = DownloadManager.Instance;
+ }
+
+ // 打开文件
+ private void OpenFile_Click(object sender, RoutedEventArgs e)
+ {
+ if (DownloadGrid.SelectedItem is DownloadTask task && task.IsComplete)
+ {
+ try { Process.Start(new ProcessStartInfo(task.FullPath) { UseShellExecute = true }); } catch { }
+ }
+ }
+
+ // 打开文件夹
+ private void OpenFolder_Click(object sender, RoutedEventArgs e)
+ {
+ if (DownloadGrid.SelectedItem is DownloadTask task && task.IsComplete)
+ {
+ try { Process.Start("explorer.exe", $"/select,\"{task.FullPath}\""); } catch { }
+ }
+ }
+
+ // 取消按钮点击事件
+ private void Cancel_Click(object sender, RoutedEventArgs e)
+ {
+ if ((sender as Button)?.DataContext is DownloadTask task && !task.IsComplete)
+ {
+ task.Cancel();
+ }
+ }
+
+ // 清除已完成按钮点击事件
+ private void ClearCompleted_Click(object sender, RoutedEventArgs e)
+ {
+ var completed = DownloadManager.Instance.Tasks.Where(t => t.IsComplete).ToList();
+ foreach (var t in completed)
+ {
+ DownloadManager.Instance.Tasks.Remove(t);
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/csharp/BrowserTool/BrowserTool/Browser/DownloadTask.cs b/csharp/BrowserTool/BrowserTool/Browser/DownloadTask.cs
new file mode 100644
index 0000000000000000000000000000000000000000..6f218068141b3f218efc00ad0e30a3b68db80cb4
--- /dev/null
+++ b/csharp/BrowserTool/BrowserTool/Browser/DownloadTask.cs
@@ -0,0 +1,131 @@
+using System;
+using System.ComponentModel;
+using CefSharp;
+
+namespace BrowserTool.Browser
+{
+ ///
+ /// 下载任务数据结构,支持属性变更通知
+ ///
+ public class DownloadTask : INotifyPropertyChanged
+ {
+ private string _fileName;
+ private string _fullPath;
+ private long _receivedBytes;
+ private long _totalBytes;
+ private bool _isComplete;
+ private bool _isCancelled;
+ private bool _isError;
+ private string _status;
+
+ public string FileName
+ {
+ get => _fileName;
+ set
+ {
+ _fileName = value;
+ OnPropertyChanged(nameof(FileName));
+ }
+ }
+
+ public string FullPath
+ {
+ get => _fullPath;
+ set
+ {
+ _fullPath = value;
+ OnPropertyChanged(nameof(FullPath));
+ }
+ }
+
+ public long ReceivedBytes
+ {
+ get => _receivedBytes;
+ set
+ {
+ _receivedBytes = value;
+ OnPropertyChanged(nameof(ReceivedBytes));
+ OnPropertyChanged(nameof(Progress));
+ }
+ }
+
+ public long TotalBytes
+ {
+ get => _totalBytes;
+ set
+ {
+ _totalBytes = value;
+ OnPropertyChanged(nameof(TotalBytes));
+ OnPropertyChanged(nameof(Progress));
+ }
+ }
+
+ public bool IsComplete
+ {
+ get => _isComplete;
+ set
+ {
+ _isComplete = value;
+ OnPropertyChanged(nameof(IsComplete));
+ }
+ }
+
+ public bool IsCancelled
+ {
+ get => _isCancelled;
+ set
+ {
+ _isCancelled = value;
+ OnPropertyChanged(nameof(IsCancelled));
+ }
+ }
+
+ public bool IsError
+ {
+ get => _isError;
+ set
+ {
+ _isError = value;
+ OnPropertyChanged(nameof(IsError));
+ }
+ }
+
+ public string Status
+ {
+ get => _status;
+ set
+ {
+ _status = value;
+ OnPropertyChanged(nameof(Status));
+ }
+ }
+
+ public DateTime StartTime { get; set; } = DateTime.Now;
+
+ // 下载回调,用于取消下载
+ [Newtonsoft.Json.JsonIgnore]
+ public IDownloadItemCallback Callback { get; set; }
+
+ public event PropertyChangedEventHandler PropertyChanged;
+ protected void OnPropertyChanged(string name)
+ {
+ PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
+ }
+
+ public double Progress => TotalBytes > 0 ? (double)ReceivedBytes / TotalBytes : 0;
+
+ ///
+ /// 取消下载
+ ///
+ public void Cancel()
+ {
+ if (Callback != null && !Callback.IsDisposed)
+ {
+ Callback.Cancel();
+ IsCancelled = true;
+ Status = "已取消";
+ IsComplete = true;
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/csharp/BrowserTool/BrowserTool/Browser/InverseBoolConverter.cs b/csharp/BrowserTool/BrowserTool/Browser/InverseBoolConverter.cs
new file mode 100644
index 0000000000000000000000000000000000000000..2293ae56345fb0b16359c0879166433d7a0ad15b
--- /dev/null
+++ b/csharp/BrowserTool/BrowserTool/Browser/InverseBoolConverter.cs
@@ -0,0 +1,23 @@
+using System;
+using System.Globalization;
+using System.Windows.Data;
+
+namespace BrowserTool.Browser
+{
+ ///
+ /// 反转布尔值转换器
+ ///
+ public class InverseBoolConverter : IValueConverter
+ {
+ public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+ {
+ if (value is bool b) return !b;
+ return value;
+ }
+ public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+ {
+ if (value is bool b) return !b;
+ return value;
+ }
+ }
+}
\ No newline at end of file
diff --git a/csharp/BrowserTool/BrowserTool/BrowserTool.csproj b/csharp/BrowserTool/BrowserTool/BrowserTool.csproj
new file mode 100644
index 0000000000000000000000000000000000000000..278f74edb4397e79c2ecc7b40e1092780bdd2379
--- /dev/null
+++ b/csharp/BrowserTool/BrowserTool/BrowserTool.csproj
@@ -0,0 +1,64 @@
+
+
+ WinExe
+ net8.0-windows
+ true
+ true
+ BrowserTool
+ BrowserTool
+ Resources\app.ico
+ AnyCPU;x64
+
+
+
+
+
+
+
+
+
+
+
+
+ all
+ runtime; build; native; contentfiles; analyzers; buildtransitive
+
+
+ all
+ runtime; build; native; contentfiles; analyzers; buildtransitive
+
+
+
+
+
+
+
+
+ PreserveNewest
+
+
+
+
+
+ PreserveNewest
+
+
+
+
+
+ Always
+
+
+ Always
+
+
+ Always
+
+
+
+
+
+ PreserveNewest
+
+
+
\ No newline at end of file
diff --git a/csharp/BrowserTool/BrowserTool/ChangePasswordWindow.xaml b/csharp/BrowserTool/BrowserTool/ChangePasswordWindow.xaml
new file mode 100644
index 0000000000000000000000000000000000000000..2a3c9385389af00f655eb9bf462a5a90e7a40ba3
--- /dev/null
+++ b/csharp/BrowserTool/BrowserTool/ChangePasswordWindow.xaml
@@ -0,0 +1,59 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/csharp/BrowserTool/BrowserTool/ChangePasswordWindow.xaml.cs b/csharp/BrowserTool/BrowserTool/ChangePasswordWindow.xaml.cs
new file mode 100644
index 0000000000000000000000000000000000000000..4bfdb956b5b418320c49c8ac0ce26d87cd870782
--- /dev/null
+++ b/csharp/BrowserTool/BrowserTool/ChangePasswordWindow.xaml.cs
@@ -0,0 +1,68 @@
+using System.Windows;
+using BrowserTool.Utils;
+
+namespace BrowserTool
+{
+ public partial class ChangePasswordWindow : Window
+ {
+ public ChangePasswordWindow()
+ {
+ InitializeComponent();
+ }
+ private void BtnOK_Click(object sender, RoutedEventArgs e)
+ {
+ if (!PasswordHelper.VerifyOrSetStartupPassword(txtOld.Password))
+ {
+ MessageBox.Show("旧密码错误!", "提示", MessageBoxButton.OK, MessageBoxImage.Error);
+ txtOld.Clear();
+ txtOld.Focus();
+ return;
+ }
+ if (string.IsNullOrWhiteSpace(txtNew1.Password) || txtNew1.Password != txtNew2.Password)
+ {
+ MessageBox.Show("两次输入的新密码不一致或为空!", "提示", MessageBoxButton.OK, MessageBoxImage.Error);
+ txtNew1.Clear();
+ txtNew2.Clear();
+ txtNew1.Focus();
+ return;
+ }
+
+ // 1. 用旧密码设置KeyManager
+ KeyManager.SetPassword(txtOld.Password);
+ var allGroups = Database.SiteConfig.GetAllGroups();
+
+
+ // 2. 用新密码设置KeyManager
+ KeyManager.SetPassword(txtNew1.Password);
+ foreach (var group in allGroups)
+ {
+ foreach (var site in group.Sites)
+ {
+ Database.SiteConfig.SaveSite(site);
+ }
+ }
+
+ // 3. 保存新启动密码
+ PasswordHelper.SaveStartupPassword(txtNew1.Password);
+ MessageBox.Show("密码修改成功!", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
+
+
+ // 4. 激活主窗口
+ if (Owner != null)
+ {
+ Owner.Show();
+ Owner.WindowState = WindowState.Normal;
+ Owner.Activate();
+ }
+
+ DialogResult = true;
+ Close();
+ //Application.Current.Shutdown();
+ }
+ private void BtnCancel_Click(object sender, RoutedEventArgs e)
+ {
+ DialogResult = false;
+ Close();
+ }
+ }
+}
\ No newline at end of file
diff --git a/csharp/BrowserTool/BrowserTool/CheckInResultQueue.cs b/csharp/BrowserTool/BrowserTool/CheckInResultQueue.cs
new file mode 100644
index 0000000000000000000000000000000000000000..0db1added3d2e0efec3e661bd57a15f6e20e82c4
--- /dev/null
+++ b/csharp/BrowserTool/BrowserTool/CheckInResultQueue.cs
@@ -0,0 +1,182 @@
+using System;
+using System.Collections.Concurrent;
+using System.Threading;
+using System.Threading.Tasks;
+using BrowserTool.Utils;
+using NLog;
+
+namespace BrowserTool
+{
+ ///
+ /// 打卡结果数据
+ ///
+ public class CheckInResult
+ {
+ ///
+ /// 是否成功
+ ///
+ public bool IsSuccess { get; set; }
+
+ ///
+ /// 页面URL
+ ///
+ public string Url { get; set; } = string.Empty;
+
+ ///
+ /// 检查时间
+ ///
+ public DateTime CheckTime { get; set; } = DateTime.Now;
+
+ ///
+ /// 备注信息
+ ///
+ public string Message { get; set; } = string.Empty;
+ }
+
+ ///
+ /// 打卡结果队列管理器
+ ///
+ public class CheckInResultQueue
+ {
+ private static readonly Logger _logger = LogManager.GetCurrentClassLogger();
+ private static readonly Lazy _instance = new(() => new CheckInResultQueue());
+
+ ///
+ /// 单例实例
+ ///
+ public static CheckInResultQueue Instance => _instance.Value;
+
+ ///
+ /// 结果队列
+ ///
+ private readonly ConcurrentQueue _resultQueue = new();
+
+ ///
+ /// 等待结果的信号量
+ ///
+ private readonly SemaphoreSlim _resultSemaphore = new(0);
+
+ ///
+ /// 私有构造函数
+ ///
+ private CheckInResultQueue()
+ {
+ }
+
+ ///
+ /// 添加检查结果到队列
+ ///
+ /// 检查结果
+ public void EnqueueResult(CheckInResult result)
+ {
+ try
+ {
+ _resultQueue.Enqueue(result);
+ _resultSemaphore.Release(); // 通知等待的线程
+ _logger.Debug($"添加打卡结果到队列: 成功={result.IsSuccess}, URL={result.Url}, 消息={result.Message}");
+ }
+ catch (Exception ex)
+ {
+ _logger.Error("添加结果到队列时发生异常", ex);
+ }
+ }
+
+ ///
+ /// 从队列获取检查结果(带超时)
+ ///
+ /// 超时时间(分钟)
+ /// 检查结果,超时返回null
+ public async Task DequeueResultAsync(int timeoutMinutes = 2)
+ {
+ try
+ {
+ _logger.Debug($"开始等待打卡结果,超时时间: {timeoutMinutes}分钟");
+
+ // 等待结果或超时
+ var timeout = TimeSpan.FromMinutes(timeoutMinutes);
+ bool hasResult = await _resultSemaphore.WaitAsync(timeout);
+
+ if (hasResult)
+ {
+ if (_resultQueue.TryDequeue(out CheckInResult? result))
+ {
+ _logger.Debug($"成功获取打卡结果: 成功={result.IsSuccess}, URL={result.Url}");
+ return result;
+ }
+ else
+ {
+ _logger.Warn("信号量被释放但队列为空");
+ return null;
+ }
+ }
+ else
+ {
+ _logger.Debug($"等待打卡结果超时({timeoutMinutes}分钟)");
+ return null;
+ }
+ }
+ catch (Exception ex)
+ {
+ _logger.Error("从队列获取结果时发生异常", ex);
+ return null;
+ }
+ }
+
+ ///
+ /// 清空队列
+ ///
+ public async Task ClearAsync()
+ {
+ try
+ {
+ while (_resultQueue.TryDequeue(out _))
+ {
+ // 清空队列
+ }
+
+ // 重置信号量
+ while (_resultSemaphore.CurrentCount > 0)
+ {
+ await _resultSemaphore.WaitAsync(0);
+ }
+
+ _logger.Debug("打卡结果队列已清空");
+ }
+ catch (Exception ex)
+ {
+ _logger.Error("清空队列时发生异常", ex);
+ }
+ }
+
+ ///
+ /// 清空队列(同步版本)
+ ///
+ public void Clear()
+ {
+ try
+ {
+ while (_resultQueue.TryDequeue(out _))
+ {
+ // 清空队列
+ }
+
+ // 重置信号量(同步方式)
+ while (_resultSemaphore.CurrentCount > 0)
+ {
+ _resultSemaphore.Wait(0);
+ }
+
+ _logger.Debug("打卡结果队列已清空");
+ }
+ catch (Exception ex)
+ {
+ _logger.Error("清空队列时发生异常", ex);
+ }
+ }
+
+ ///
+ /// 获取队列中的结果数量
+ ///
+ public int Count => _resultQueue.Count;
+ }
+}
\ No newline at end of file
diff --git a/csharp/BrowserTool/BrowserTool/Controls/LoadingControl.xaml b/csharp/BrowserTool/BrowserTool/Controls/LoadingControl.xaml
new file mode 100644
index 0000000000000000000000000000000000000000..6ebf053ed9f85c9cfa7527f285ac7d81c043ff47
--- /dev/null
+++ b/csharp/BrowserTool/BrowserTool/Controls/LoadingControl.xaml
@@ -0,0 +1,67 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/csharp/BrowserTool/BrowserTool/Controls/LoadingControl.xaml.cs b/csharp/BrowserTool/BrowserTool/Controls/LoadingControl.xaml.cs
new file mode 100644
index 0000000000000000000000000000000000000000..befcaf39ac7bae6c8deda7d68521e88b144239fc
--- /dev/null
+++ b/csharp/BrowserTool/BrowserTool/Controls/LoadingControl.xaml.cs
@@ -0,0 +1,25 @@
+using System.Windows;
+using System.Windows.Controls;
+
+namespace BrowserTool.Controls
+{
+ ///
+ /// LoadingControl.xaml 的交互逻辑
+ ///
+ public partial class LoadingControl : UserControl
+ {
+ public static readonly DependencyProperty IsLoadingProperty =
+ DependencyProperty.Register("IsLoading", typeof(bool), typeof(LoadingControl), new PropertyMetadata(false));
+
+ public bool IsLoading
+ {
+ get { return (bool)GetValue(IsLoadingProperty); }
+ set { SetValue(IsLoadingProperty, value); }
+ }
+
+ public LoadingControl()
+ {
+ InitializeComponent();
+ }
+ }
+}
\ No newline at end of file
diff --git a/csharp/BrowserTool/BrowserTool/Controls/SearchBar.xaml b/csharp/BrowserTool/BrowserTool/Controls/SearchBar.xaml
new file mode 100644
index 0000000000000000000000000000000000000000..c16559596823b5c9a3ea659c59e7384b9932ced3
--- /dev/null
+++ b/csharp/BrowserTool/BrowserTool/Controls/SearchBar.xaml
@@ -0,0 +1,193 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/csharp/BrowserTool/BrowserTool/Controls/SearchBar.xaml.cs b/csharp/BrowserTool/BrowserTool/Controls/SearchBar.xaml.cs
new file mode 100644
index 0000000000000000000000000000000000000000..b04c10b70f67621d4cfa64fb5c116f49904deacd
--- /dev/null
+++ b/csharp/BrowserTool/BrowserTool/Controls/SearchBar.xaml.cs
@@ -0,0 +1,221 @@
+using System;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Input;
+using CefSharp;
+using CefSharp.Wpf;
+
+namespace BrowserTool.Controls
+{
+ ///
+ /// SearchBar.xaml 的交互逻辑
+ ///
+ public partial class SearchBar : UserControl
+ {
+ private ChromiumWebBrowser _browser;
+ private int _currentMatchIndex = 0;
+ private int _totalMatches = 0;
+ private bool _isMatchCase = false;
+
+ public event EventHandler CloseRequested;
+
+ public bool IsMatchCase
+ {
+ get { return _isMatchCase; }
+ set
+ {
+ _isMatchCase = value;
+ UpdateMatchCaseButtonStyle();
+ }
+ }
+
+ public SearchBar()
+ {
+ InitializeComponent();
+ UpdateUI();
+ }
+
+ public void SetBrowser(ChromiumWebBrowser browser)
+ {
+ _browser = browser;
+ }
+
+ public void FocusSearchBox()
+ {
+ SearchTextBox.Focus();
+ SearchTextBox.SelectAll();
+ }
+
+ private void SearchTextBox_TextChanged(object sender, TextChangedEventArgs e)
+ {
+ var searchText = SearchTextBox.Text;
+
+ if (string.IsNullOrEmpty(searchText))
+ {
+ StopFind();
+ return;
+ }
+
+ StartFind(searchText);
+ }
+
+ private void SearchTextBox_KeyDown(object sender, KeyEventArgs e)
+ {
+ switch (e.Key)
+ {
+ case Key.Enter:
+ if (Keyboard.Modifiers == ModifierKeys.Shift)
+ {
+ FindPrevious();
+ }
+ else
+ {
+ FindNext();
+ }
+ e.Handled = true;
+ break;
+ case Key.Escape:
+ CloseRequested?.Invoke(this, EventArgs.Empty);
+ e.Handled = true;
+ break;
+ }
+ }
+
+ private void PreviousButton_Click(object sender, RoutedEventArgs e)
+ {
+ FindPrevious();
+ }
+
+ private void NextButton_Click(object sender, RoutedEventArgs e)
+ {
+ FindNext();
+ }
+
+ private void MatchCaseButton_Click(object sender, RoutedEventArgs e)
+ {
+ IsMatchCase = !IsMatchCase;
+
+ // 重新搜索
+ var searchText = SearchTextBox.Text;
+ if (!string.IsNullOrEmpty(searchText))
+ {
+ StartFind(searchText);
+ }
+ }
+
+ private void CloseButton_Click(object sender, RoutedEventArgs e)
+ {
+ CloseRequested?.Invoke(this, EventArgs.Empty);
+ }
+
+ private void StartFind(string searchText)
+ {
+ if (_browser == null || !_browser.IsBrowserInitialized)
+ return;
+
+ try
+ {
+ _browser.Find(searchText, forward: true, matchCase: IsMatchCase, findNext: false);
+
+ // 简单的UI更新,显示搜索中状态
+ ResultCountText.Text = "搜索中...";
+ SearchTextBox.Background = System.Windows.Media.Brushes.DarkSlateGray;
+
+ // 启用按钮
+ PreviousButton.IsEnabled = true;
+ NextButton.IsEnabled = true;
+ }
+ catch (Exception ex)
+ {
+ ResultCountText.Text = "搜索失败";
+ SearchTextBox.Background = System.Windows.Media.Brushes.DarkRed;
+ }
+ }
+
+ private void FindNext()
+ {
+ var searchText = SearchTextBox.Text;
+ if (string.IsNullOrEmpty(searchText) || _browser == null || !_browser.IsBrowserInitialized)
+ return;
+
+ try
+ {
+ _browser.Find(searchText, forward: true, matchCase: IsMatchCase, findNext: true);
+ }
+ catch (Exception ex)
+ {
+ // 忽略错误
+ }
+ }
+
+ private void FindPrevious()
+ {
+ var searchText = SearchTextBox.Text;
+ if (string.IsNullOrEmpty(searchText) || _browser == null || !_browser.IsBrowserInitialized)
+ return;
+
+ try
+ {
+ _browser.Find(searchText, forward: false, matchCase: IsMatchCase, findNext: true);
+ }
+ catch (Exception ex)
+ {
+ // 忽略错误
+ }
+ }
+
+ private void StopFind()
+ {
+ if (_browser == null || !_browser.IsBrowserInitialized)
+ return;
+
+ try
+ {
+ _browser.StopFinding(clearSelection: true);
+ }
+ catch (Exception ex)
+ {
+ // 忽略错误
+ }
+
+ _currentMatchIndex = 0;
+ _totalMatches = 0;
+ UpdateUI();
+ }
+
+ private void UpdateUI()
+ {
+ if (_totalMatches > 0)
+ {
+ ResultCountText.Text = $"{_currentMatchIndex}/{_totalMatches}";
+ SearchTextBox.Background = System.Windows.Media.Brushes.DarkSlateGray;
+ }
+ else if (!string.IsNullOrEmpty(SearchTextBox.Text))
+ {
+ ResultCountText.Text = "0/0";
+ SearchTextBox.Background = System.Windows.Media.Brushes.DarkRed;
+ }
+ else
+ {
+ ResultCountText.Text = "0/0";
+ SearchTextBox.Background = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(30, 30, 30));
+ }
+
+ PreviousButton.IsEnabled = !string.IsNullOrEmpty(SearchTextBox.Text);
+ NextButton.IsEnabled = !string.IsNullOrEmpty(SearchTextBox.Text);
+ }
+
+ private void UpdateMatchCaseButtonStyle()
+ {
+ // 触发数据绑定更新
+ var binding = MatchCaseButton.GetBindingExpression(Button.StyleProperty);
+ binding?.UpdateTarget();
+ }
+
+ public void Clear()
+ {
+ SearchTextBox.Clear();
+ StopFind();
+ }
+ }
+}
diff --git a/csharp/BrowserTool/BrowserTool/Converters/BooleanToVisibilityConverter.cs b/csharp/BrowserTool/BrowserTool/Converters/BooleanToVisibilityConverter.cs
new file mode 100644
index 0000000000000000000000000000000000000000..900600482edc7a2b4f52aada1d6496f14661491e
--- /dev/null
+++ b/csharp/BrowserTool/BrowserTool/Converters/BooleanToVisibilityConverter.cs
@@ -0,0 +1,28 @@
+using System;
+using System.Globalization;
+using System.Windows;
+using System.Windows.Data;
+
+namespace BrowserTool.Converters
+{
+ public class BooleanToVisibilityConverter : IValueConverter
+ {
+ public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+ {
+ if (value is bool boolValue)
+ {
+ return boolValue ? Visibility.Visible : Visibility.Collapsed;
+ }
+ return Visibility.Collapsed;
+ }
+
+ public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+ {
+ if (value is Visibility visibility)
+ {
+ return visibility == Visibility.Visible;
+ }
+ return false;
+ }
+ }
+}
\ No newline at end of file
diff --git a/csharp/BrowserTool/BrowserTool/Database/AppDbContext.cs b/csharp/BrowserTool/BrowserTool/Database/AppDbContext.cs
new file mode 100644
index 0000000000000000000000000000000000000000..0b1a0d000313ee9a408225d276665a439389363b
--- /dev/null
+++ b/csharp/BrowserTool/BrowserTool/Database/AppDbContext.cs
@@ -0,0 +1,100 @@
+using Microsoft.EntityFrameworkCore;
+using System;
+
+namespace BrowserTool.Database
+{
+ ///
+ /// 应用程序数据库上下文
+ ///
+ public class AppDbContext : DbContext
+ {
+ ///
+ /// 站点组集合
+ ///
+ public DbSet SiteGroups { get; set; }
+
+ ///
+ /// 站点项集合
+ ///
+ public DbSet SiteItems { get; set; }
+
+ ///
+ /// 配置数据库连接
+ ///
+ /// 数据库上下文选项构建器
+ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
+ {
+ try
+ {
+ var dbPath = DatabaseInitializer.GetDbPath();
+ optionsBuilder.UseSqlite($"Data Source={dbPath}");
+ }
+ catch (Exception ex)
+ {
+ throw new Exception($"配置数据库连接时出错:{ex.Message}", ex);
+ }
+ }
+
+ ///
+ /// 配置实体模型
+ ///
+ /// 模型构建器
+ protected override void OnModelCreating(ModelBuilder modelBuilder)
+ {
+ try
+ {
+ // 配置 SiteGroup 实体
+ modelBuilder.Entity(entity =>
+ {
+ entity.HasKey(e => e.Id);
+ entity.Property(e => e.Name).IsRequired().HasMaxLength(100);
+ entity.Property(e => e.SortOrder).HasDefaultValue(0);
+ entity.Property(e => e.IsEnabled).HasDefaultValue(true);
+ entity.Property(e => e.IsDefaultExpanded).HasDefaultValue(false);
+ entity.Property(e => e.CreateTime).HasDefaultValueSql("CURRENT_TIMESTAMP");
+ entity.Property(e => e.UpdateTime).HasDefaultValueSql("CURRENT_TIMESTAMP");
+ });
+
+ // 配置 SiteItem 实体
+ modelBuilder.Entity(entity =>
+ {
+ entity.HasKey(e => e.Id);
+ entity.Property(e => e.DisplayName).IsRequired().HasMaxLength(200);
+ entity.Property(e => e.Url).IsRequired().HasMaxLength(500);
+ entity.Property(e => e.SortOrder).HasDefaultValue(0);
+ entity.Property(e => e.Username).HasMaxLength(200);
+ entity.Property(e => e.Password).HasMaxLength(200);
+ entity.Property(e => e.CommonUsername).HasMaxLength(200);
+ entity.Property(e => e.CommonPassword).HasMaxLength(200);
+ entity.Property(e => e.UseCommonCredentials).HasDefaultValue(false);
+ entity.Property(e => e.AutoLogin).HasDefaultValue(false);
+ entity.Property(e => e.IsEnabled).HasDefaultValue(true);
+ entity.Property(e => e.Icon).HasMaxLength(1000);
+ entity.Property(e => e.Description).HasMaxLength(1000);
+ entity.Property(e => e.Tags).HasMaxLength(500);
+ entity.Property(e => e.CreateTime).HasDefaultValueSql("CURRENT_TIMESTAMP");
+ entity.Property(e => e.UpdateTime).HasDefaultValueSql("CURRENT_TIMESTAMP");
+ entity.Property(e => e.AccessCount).HasDefaultValue(0);
+ entity.Property(e => e.UsernameSelector).HasMaxLength(200);
+ entity.Property(e => e.PasswordSelector).HasMaxLength(200);
+ entity.Property(e => e.CaptchaSelector).HasMaxLength(200);
+ entity.Property(e => e.LoginButtonSelector).HasMaxLength(200);
+ entity.Property(e => e.LoginPageFeature).HasMaxLength(500);
+ entity.Property(e => e.CaptchaValue).HasMaxLength(200);
+ entity.Property(e => e.CaptchaMode).HasDefaultValue(0);
+ entity.Property(e => e.GoogleSecret).HasMaxLength(200);
+
+ // 配置外键关系
+ entity.HasOne(e => e.Group)
+ .WithMany(g => g.Sites)
+ .HasForeignKey(e => e.GroupId)
+ .OnDelete(DeleteBehavior.Cascade);
+ });
+ }
+ catch (Exception ex)
+ {
+ throw new Exception($"配置实体模型时出错:{ex.Message}", ex);
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/csharp/BrowserTool/BrowserTool/Database/ApplicationDbContext.cs b/csharp/BrowserTool/BrowserTool/Database/ApplicationDbContext.cs
new file mode 100644
index 0000000000000000000000000000000000000000..0f47a1e24816f707158d9f67ad90634ada252095
--- /dev/null
+++ b/csharp/BrowserTool/BrowserTool/Database/ApplicationDbContext.cs
@@ -0,0 +1,58 @@
+using BrowserTool.Database.Entities;
+using Microsoft.EntityFrameworkCore;
+using System;
+using System.IO;
+
+namespace BrowserTool.Database
+{
+ public class ApplicationDbContext : DbContext
+ {
+ private static readonly string DbPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "sites.db");
+
+ public DbSet SiteGroups { get; set; }
+ public DbSet SiteItems { get; set; }
+
+ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
+ {
+ optionsBuilder.UseSqlite($"Data Source={DbPath}");
+ }
+
+ protected override void OnModelCreating(ModelBuilder modelBuilder)
+ {
+ base.OnModelCreating(modelBuilder);
+
+ // Configure SiteGroup
+ modelBuilder.Entity(entity =>
+ {
+ entity.HasKey(e => e.Id);
+ entity.Property(e => e.Name).IsRequired().HasMaxLength(100);
+ entity.Property(e => e.CreateTime).HasDefaultValueSql("CURRENT_TIMESTAMP");
+ entity.Property(e => e.UpdateTime).HasDefaultValueSql("CURRENT_TIMESTAMP");
+ entity.Property(e => e.IsEnabled).HasDefaultValue(true);
+ entity.Property(e => e.SortOrder).HasDefaultValue(0);
+ });
+
+ // Configure SiteItem
+ modelBuilder.Entity(entity =>
+ {
+ entity.HasKey(e => e.Id);
+ entity.Property(e => e.DisplayName).IsRequired().HasMaxLength(200);
+ entity.Property(e => e.Url).IsRequired().HasMaxLength(500);
+ entity.Property(e => e.CreateTime).HasDefaultValueSql("CURRENT_TIMESTAMP");
+ entity.Property(e => e.UpdateTime).HasDefaultValueSql("CURRENT_TIMESTAMP");
+ entity.Property(e => e.IsEnabled).HasDefaultValue(true);
+ entity.Property(e => e.SortOrder).HasDefaultValue(0);
+ entity.Property(e => e.UseCommonCredentials).HasDefaultValue(false);
+ entity.Property(e => e.AutoLogin).HasDefaultValue(false);
+ entity.Property(e => e.AccessCount).HasDefaultValue(0);
+ entity.Property(e => e.CaptchaMode).HasDefaultValue(0);
+
+ // Configure relationship
+ entity.HasOne(e => e.Group)
+ .WithMany(g => g.Sites)
+ .HasForeignKey(e => e.GroupId)
+ .OnDelete(DeleteBehavior.Cascade);
+ });
+ }
+ }
+}
\ No newline at end of file
diff --git a/csharp/BrowserTool/BrowserTool/Database/DatabaseInitializer.cs b/csharp/BrowserTool/BrowserTool/Database/DatabaseInitializer.cs
new file mode 100644
index 0000000000000000000000000000000000000000..492faea242c8c2fee2142cd60bc388fc37a2afc5
--- /dev/null
+++ b/csharp/BrowserTool/BrowserTool/Database/DatabaseInitializer.cs
@@ -0,0 +1,66 @@
+using System;
+using System.IO;
+using System.Linq;
+using Microsoft.EntityFrameworkCore;
+
+namespace BrowserTool.Database
+{
+ ///
+ /// 数据库初始化器
+ ///
+ public static class DatabaseInitializer
+ {
+ ///
+ /// 初始化数据库
+ ///
+ public static void Initialize()
+ {
+ // 确保数据库目录存在
+ var dbPath = GetDbPath();
+ var dbDirectory = Path.GetDirectoryName(dbPath);
+ if (!Directory.Exists(dbDirectory))
+ {
+ Directory.CreateDirectory(dbDirectory);
+ }
+
+ using (var context = new AppDbContext())
+ {
+ try
+ {
+ // 确保数据库存在
+ context.Database.EnsureCreated();
+
+ // 检查是否需要迁移
+ var pendingMigrations = context.Database.GetPendingMigrations().ToList();
+ if (pendingMigrations.Any())
+ {
+ context.Database.Migrate();
+ }
+ }
+ catch (Exception ex)
+ {
+ throw new Exception($"初始化数据库时出错:{ex.Message}", ex);
+ }
+ }
+ }
+
+ ///
+ /// 获取数据库文件路径
+ ///
+ /// 数据库文件的完整路径
+ public static string GetDbPath()
+ {
+ try
+ {
+ // 获取应用程序目录
+ var appPath = AppDomain.CurrentDomain.BaseDirectory;
+ var dbPath = Path.Combine(appPath, "sites.db");
+ return dbPath;
+ }
+ catch (Exception ex)
+ {
+ throw new Exception($"获取数据库路径时出错:{ex.Message}", ex);
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/csharp/BrowserTool/BrowserTool/Database/Entities/SiteGroup.cs b/csharp/BrowserTool/BrowserTool/Database/Entities/SiteGroup.cs
new file mode 100644
index 0000000000000000000000000000000000000000..636de23ee4de39e4c34deba6083cb8fdcb3dbbc2
--- /dev/null
+++ b/csharp/BrowserTool/BrowserTool/Database/Entities/SiteGroup.cs
@@ -0,0 +1,34 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using System.ComponentModel.DataAnnotations.Schema;
+
+namespace BrowserTool.Database.Entities
+{
+ [Table("SiteGroups")]
+ public class SiteGroup
+ {
+ [Key]
+ public int Id { get; set; }
+
+ [Required]
+ [MaxLength(100)]
+ public string Name { get; set; }
+
+ public int SortOrder { get; set; }
+
+ public bool IsEnabled { get; set; }
+
+ ///
+ /// 是否默认展开(用于控制一级菜单的默认展开状态)
+ ///
+ public bool IsDefaultExpanded { get; set; } = false;
+
+ public DateTime CreateTime { get; set; }
+
+ public DateTime UpdateTime { get; set; }
+
+ // Navigation property
+ public virtual ICollection Sites { get; set; } = new List();
+ }
+}
\ No newline at end of file
diff --git a/csharp/BrowserTool/BrowserTool/Database/Entities/SiteItem.cs b/csharp/BrowserTool/BrowserTool/Database/Entities/SiteItem.cs
new file mode 100644
index 0000000000000000000000000000000000000000..57548130880e9c19fa78e27416c047ceb8b34024
--- /dev/null
+++ b/csharp/BrowserTool/BrowserTool/Database/Entities/SiteItem.cs
@@ -0,0 +1,88 @@
+using System;
+using System.ComponentModel.DataAnnotations;
+using System.ComponentModel.DataAnnotations.Schema;
+
+namespace BrowserTool.Database.Entities
+{
+ [Table("SiteItems")]
+ public class SiteItem
+ {
+ [Key]
+ public int Id { get; set; }
+
+ [Required]
+ public int GroupId { get; set; }
+
+ [Required]
+ [MaxLength(200)]
+ public string DisplayName { get; set; }
+
+ [Required]
+ [MaxLength(500)]
+ public string Url { get; set; }
+
+ public int SortOrder { get; set; }
+
+ [MaxLength(200)]
+ public string Username { get; set; }
+
+ [MaxLength(200)]
+ public string Password { get; set; }
+
+ [MaxLength(200)]
+ public string CommonUsername { get; set; }
+
+ [MaxLength(200)]
+ public string CommonPassword { get; set; }
+
+ public bool UseCommonCredentials { get; set; }
+
+ public bool AutoLogin { get; set; }
+
+ public bool IsEnabled { get; set; }
+
+ [MaxLength(1000)]
+ public string Icon { get; set; }
+
+ [MaxLength(1000)]
+ public string Description { get; set; }
+
+ [MaxLength(500)]
+ public string Tags { get; set; }
+
+ public DateTime CreateTime { get; set; }
+
+ public DateTime UpdateTime { get; set; }
+
+ public DateTime? LastAccessTime { get; set; }
+
+ public int AccessCount { get; set; }
+
+ [MaxLength(200)]
+ public string UsernameSelector { get; set; }
+
+ [MaxLength(200)]
+ public string PasswordSelector { get; set; }
+
+ [MaxLength(200)]
+ public string CaptchaSelector { get; set; }
+
+ [MaxLength(200)]
+ public string LoginButtonSelector { get; set; }
+
+ [MaxLength(500)]
+ public string LoginPageFeature { get; set; }
+
+ [MaxLength(200)]
+ public string CaptchaValue { get; set; }
+
+ public int CaptchaMode { get; set; }
+
+ [MaxLength(200)]
+ public string GoogleSecret { get; set; }
+
+ // Navigation property
+ [ForeignKey("GroupId")]
+ public virtual SiteGroup Group { get; set; }
+ }
+}
\ No newline at end of file
diff --git a/csharp/BrowserTool/BrowserTool/Database/Migrations/AddIsDefaultExpandedToSiteGroup.cs b/csharp/BrowserTool/BrowserTool/Database/Migrations/AddIsDefaultExpandedToSiteGroup.cs
new file mode 100644
index 0000000000000000000000000000000000000000..bbf881d42febb584f0d87c577fa8fb12050562cd
--- /dev/null
+++ b/csharp/BrowserTool/BrowserTool/Database/Migrations/AddIsDefaultExpandedToSiteGroup.cs
@@ -0,0 +1,24 @@
+using Microsoft.EntityFrameworkCore.Migrations;
+
+namespace BrowserTool.Database.Migrations
+{
+ public partial class AddIsDefaultExpandedToSiteGroup : Migration
+ {
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.AddColumn(
+ name: "IsDefaultExpanded",
+ table: "SiteGroups",
+ type: "INTEGER",
+ nullable: false,
+ defaultValue: false);
+ }
+
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropColumn(
+ name: "IsDefaultExpanded",
+ table: "SiteGroups");
+ }
+ }
+}
diff --git a/csharp/BrowserTool/BrowserTool/Database/Migrations/InitialCreate.cs b/csharp/BrowserTool/BrowserTool/Database/Migrations/InitialCreate.cs
new file mode 100644
index 0000000000000000000000000000000000000000..9e5206ff23a2379280dc03f2bd401305ed1cc991
--- /dev/null
+++ b/csharp/BrowserTool/BrowserTool/Database/Migrations/InitialCreate.cs
@@ -0,0 +1,104 @@
+using System;
+using Microsoft.EntityFrameworkCore.Migrations;
+
+namespace BrowserTool.Database.Migrations
+{
+ public partial class InitialCreate : Migration
+ {
+ ///
+ /// 创建数据库表结构
+ ///
+ /// 迁移构建器
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.CreateTable(
+ name: "SiteGroups",
+ columns: table => new
+ {
+ Id = table.Column(type: "INTEGER", nullable: false)
+ .Annotation("Sqlite:Autoincrement", true),
+ Name = table.Column(type: "TEXT", maxLength: 100, nullable: false),
+ SortOrder = table.Column(type: "INTEGER", nullable: false, defaultValue: 0),
+ IsEnabled = table.Column(type: "INTEGER", nullable: false, defaultValue: true),
+ CreateTime = table.Column(type: "TEXT", nullable: false, defaultValueSql: "CURRENT_TIMESTAMP"),
+ UpdateTime = table.Column(type: "TEXT", nullable: false, defaultValueSql: "CURRENT_TIMESTAMP")
+ },
+ constraints: table =>
+ {
+ table.PrimaryKey("PK_SiteGroups", x => x.Id);
+ });
+
+ migrationBuilder.CreateTable(
+ name: "SiteItems",
+ columns: table => new
+ {
+ Id = table.Column(type: "INTEGER", nullable: false)
+ .Annotation("Sqlite:Autoincrement", true),
+ GroupId = table.Column(type: "INTEGER", nullable: false),
+ DisplayName = table.Column(type: "TEXT", maxLength: 200, nullable: false),
+ Url = table.Column(type: "TEXT", maxLength: 500, nullable: false),
+ SortOrder = table.Column(type: "INTEGER", nullable: false, defaultValue: 0),
+ Username = table.Column(type: "TEXT", maxLength: 200, nullable: true),
+ Password = table.Column(type: "TEXT", maxLength: 200, nullable: true),
+ CommonUsername = table.Column(type: "TEXT", maxLength: 200, nullable: true),
+ CommonPassword = table.Column(type: "TEXT", maxLength: 200, nullable: true),
+ UseCommonCredentials = table.Column(type: "INTEGER", nullable: false, defaultValue: false),
+ AutoLogin = table.Column(type: "INTEGER", nullable: false, defaultValue: false),
+ IsEnabled = table.Column(type: "INTEGER", nullable: false, defaultValue: true),
+ Icon = table.Column(type: "TEXT", maxLength: 1000, nullable: true),
+ Description = table.Column(type: "TEXT", maxLength: 1000, nullable: true),
+ Tags = table.Column(type: "TEXT", maxLength: 500, nullable: true),
+ CreateTime = table.Column(type: "TEXT", nullable: false, defaultValueSql: "CURRENT_TIMESTAMP"),
+ UpdateTime = table.Column(type: "TEXT", nullable: false, defaultValueSql: "CURRENT_TIMESTAMP"),
+ LastAccessTime = table.Column(type: "TEXT", nullable: true),
+ AccessCount = table.Column(type: "INTEGER", nullable: false, defaultValue: 0),
+ UsernameSelector = table.Column(type: "TEXT", maxLength: 200, nullable: true),
+ PasswordSelector = table.Column(type: "TEXT", maxLength: 200, nullable: true),
+ CaptchaSelector = table.Column(type: "TEXT", maxLength: 200, nullable: true),
+ LoginButtonSelector = table.Column(type: "TEXT", maxLength: 200, nullable: true),
+ LoginPageFeature = table.Column(type: "TEXT", maxLength: 500, nullable: true),
+ CaptchaValue = table.Column(type: "TEXT", maxLength: 200, nullable: true),
+ CaptchaMode = table.Column(type: "INTEGER", nullable: false, defaultValue: 0),
+ GoogleSecret = table.Column(type: "TEXT", maxLength: 200, nullable: true)
+ },
+ constraints: table =>
+ {
+ table.PrimaryKey("PK_SiteItems", x => x.Id);
+ table.ForeignKey(
+ name: "FK_SiteItems_SiteGroups_GroupId",
+ column: x => x.GroupId,
+ principalTable: "SiteGroups",
+ principalColumn: "Id",
+ onDelete: ReferentialAction.Cascade);
+ });
+
+ migrationBuilder.CreateIndex(
+ name: "IX_SiteItems_GroupId",
+ table: "SiteItems",
+ column: "GroupId");
+
+ migrationBuilder.CreateIndex(
+ name: "IX_SiteItems_SortOrder",
+ table: "SiteItems",
+ column: "SortOrder");
+
+ migrationBuilder.CreateIndex(
+ name: "IX_SiteGroups_SortOrder",
+ table: "SiteGroups",
+ column: "SortOrder");
+ }
+
+ ///
+ /// 删除数据库表结构
+ ///
+ /// 迁移构建器
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropTable(
+ name: "SiteItems");
+
+ migrationBuilder.DropTable(
+ name: "SiteGroups");
+ }
+ }
+}
\ No newline at end of file
diff --git a/csharp/BrowserTool/BrowserTool/Database/SiteConfig.cs b/csharp/BrowserTool/BrowserTool/Database/SiteConfig.cs
new file mode 100644
index 0000000000000000000000000000000000000000..7377f6134be459197022dfbdd482e19e7c6bdf6d
--- /dev/null
+++ b/csharp/BrowserTool/BrowserTool/Database/SiteConfig.cs
@@ -0,0 +1,553 @@
+using BrowserTool.Database.Entities;
+using BrowserTool.Utils;
+using Microsoft.EntityFrameworkCore;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace BrowserTool.Database
+{
+ public static class SiteConfig
+ {
+ ///
+ /// 添加数据变更事件
+ ///
+ public static event EventHandler DataChanged;
+
+ ///
+ /// 触发数据变更事件的方法
+ ///
+ private static void OnDataChanged()
+ {
+ DataChanged?.Invoke(null, EventArgs.Empty);
+ }
+
+ ///
+ /// 解密网站敏感信息
+ ///
+ /// 要解密的网站对象
+ private static void DecryptSiteInfo(SiteItem site)
+ {
+ if (site == null) return;
+
+ try
+ {
+ // 检查DisplayName和Url是否已经是明文
+ bool isDisplayNameEncrypted = IsEncryptedString(site.DisplayName);
+ bool isUrlEncrypted = IsEncryptedString(site.Url);
+
+
+ if (!string.IsNullOrEmpty(site.Username))
+ {
+ try { site.Username = CryptoHelper.Decrypt(site.Username); }
+ catch (Exception ex) { System.Diagnostics.Debug.WriteLine($"解密Username失败: {ex}"); }
+ }
+ if (!string.IsNullOrEmpty(site.Password))
+ {
+ try { site.Password = CryptoHelper.Decrypt(site.Password); }
+ catch (Exception ex) { System.Diagnostics.Debug.WriteLine($"解密Password失败: {ex}"); }
+ }
+ if (!string.IsNullOrEmpty(site.CommonUsername))
+ {
+ try { site.CommonUsername = CryptoHelper.Decrypt(site.CommonUsername); }
+ catch (Exception ex) { System.Diagnostics.Debug.WriteLine($"解密CommonUsername失败: {ex}"); }
+ }
+ if (!string.IsNullOrEmpty(site.CommonPassword))
+ {
+ try { site.CommonPassword = CryptoHelper.Decrypt(site.CommonPassword); }
+ catch (Exception ex) { System.Diagnostics.Debug.WriteLine($"解密CommonPassword失败: {ex}"); }
+ }
+ if (!string.IsNullOrEmpty(site.GoogleSecret))
+ {
+ try { site.GoogleSecret = CryptoHelper.Decrypt(site.GoogleSecret); }
+ catch (Exception ex) { System.Diagnostics.Debug.WriteLine($"解密GoogleSecret失败: {ex}"); }
+ }
+ if (!string.IsNullOrEmpty(site.Url) && isUrlEncrypted)
+ {
+ try { site.Url = CryptoHelper.Decrypt(site.Url); }
+ catch (Exception ex) { System.Diagnostics.Debug.WriteLine($"解密Url失败: {ex}"); }
+ }
+ if (!string.IsNullOrEmpty(site.DisplayName) && isDisplayNameEncrypted)
+ {
+ try { site.DisplayName = CryptoHelper.Decrypt(site.DisplayName); }
+ catch (Exception ex) { System.Diagnostics.Debug.WriteLine($"解密DisplayName失败: {ex}"); }
+ }
+ }
+ catch (Exception ex)
+ {
+ System.Diagnostics.Debug.WriteLine($"解密站点信息时出错: {ex}");
+ }
+ }
+
+ private static bool IsEncryptedString(string str)
+ {
+ if (string.IsNullOrEmpty(str)) return false;
+
+ // 检查是否是有效的Base64字符串
+ if (!IsValidBase64String(str)) return false;
+
+ // 检查长度是否足够长(加密后的字符串通常较长)
+ if (str.Length < 16) return false;
+
+ return true;
+ }
+
+ private static bool IsValidBase64String(string str)
+ {
+ if (string.IsNullOrEmpty(str)) return false;
+
+ // 检查长度是否为4的倍数
+ if (str.Length % 4 != 0) return false;
+
+ // 检查是否只包含有效的Base64字符
+ foreach (char c in str)
+ {
+ if (!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '+' || c == '/' || c == '='))
+ {
+ return false;
+ }
+ }
+
+ // 检查填充字符
+ int paddingCount = str.Count(c => c == '=');
+ if (paddingCount > 2) return false;
+
+ return true;
+ }
+
+ ///
+ /// 批量解密网站敏感信息
+ ///
+ /// 要解密的网站集合
+ private static void DecryptSiteInfoBatch(ICollection sites)
+ {
+ if (sites == null) return;
+
+ foreach (var site in sites)
+ {
+ DecryptSiteInfo(site);
+ }
+ }
+
+ ///
+ /// 获取所有启用的分组
+ ///
+ /// 启用的分组列表
+ public static List GetGroups()
+ {
+ using (var context = new AppDbContext())
+ {
+ return context.SiteGroups
+ .Where(g => g.IsEnabled)
+ .OrderBy(g => g.SortOrder)
+ .ThenBy(g => g.Name)
+ .ToList();
+ }
+ }
+
+ ///
+ /// 根据分组ID获取该分组下的所有网站
+ ///
+ /// 分组ID
+ /// 该分组下的网站列表
+ public static List GetSitesByGroup(int groupId)
+ {
+ using (var context = new AppDbContext())
+ {
+ var sites = context.SiteItems
+ .Where(s => s.GroupId == groupId && s.IsEnabled)
+ .OrderBy(s => s.SortOrder)
+ .ThenBy(s => s.DisplayName)
+ .ToList();
+
+ // 解密敏感信息
+ DecryptSiteInfoBatch(sites);
+
+ return sites;
+ }
+ }
+
+ ///
+ /// 保存分组信息
+ ///
+ /// 要保存的分组
+ public static void SaveGroup(SiteGroup group)
+ {
+ using (var context = new AppDbContext())
+ {
+ if (group.Id == 0)
+ {
+ group.CreateTime = DateTime.Now;
+ group.UpdateTime = DateTime.Now;
+ context.SiteGroups.Add(group);
+ }
+ else
+ {
+ var existingGroup = context.SiteGroups.Find(group.Id);
+ if (existingGroup != null)
+ {
+ context.Entry(existingGroup).CurrentValues.SetValues(group);
+ existingGroup.UpdateTime = DateTime.Now;
+ }
+ }
+ context.SaveChanges();
+ OnDataChanged(); // 触发数据变更事件
+ }
+ }
+
+ ///
+ /// 保存网站信息
+ ///
+ /// 要保存的网站
+ public static void SaveSite(SiteItem site)
+ {
+ using (var context = new AppDbContext())
+ {
+ // 创建副本以避免修改原对象
+ var siteToSave = new SiteItem
+ {
+ Id = site.Id,
+ GroupId = site.GroupId,
+ DisplayName = site.DisplayName,
+ Username = site.Username,
+ Password = site.Password,
+ CommonUsername = site.CommonUsername,
+ CommonPassword = site.CommonPassword,
+ GoogleSecret = site.GoogleSecret,
+ Url = site.Url,
+ IsEnabled = site.IsEnabled,
+ SortOrder = site.SortOrder,
+ CreateTime = site.CreateTime,
+ UpdateTime = site.UpdateTime,
+ LastAccessTime = site.LastAccessTime,
+ Icon = site.Icon,
+ AccessCount = site.AccessCount
+ };
+
+ // 加密敏感信息
+ if (!string.IsNullOrEmpty(siteToSave.Username))
+ {
+ siteToSave.Username = CryptoHelper.Encrypt(siteToSave.Username);
+ }
+ if (!string.IsNullOrEmpty(siteToSave.Password))
+ {
+ siteToSave.Password = CryptoHelper.Encrypt(siteToSave.Password);
+ }
+ if (!string.IsNullOrEmpty(siteToSave.CommonUsername))
+ {
+ siteToSave.CommonUsername = CryptoHelper.Encrypt(siteToSave.CommonUsername);
+ }
+ if (!string.IsNullOrEmpty(siteToSave.CommonPassword))
+ {
+ siteToSave.CommonPassword = CryptoHelper.Encrypt(siteToSave.CommonPassword);
+ }
+ if (!string.IsNullOrEmpty(siteToSave.GoogleSecret))
+ {
+ siteToSave.GoogleSecret = CryptoHelper.Encrypt(siteToSave.GoogleSecret);
+ }
+ if (!string.IsNullOrEmpty(siteToSave.Url))
+ {
+ siteToSave.Url = CryptoHelper.Encrypt(siteToSave.Url);
+ }
+ if (!string.IsNullOrEmpty(siteToSave.DisplayName))
+ {
+ siteToSave.DisplayName = CryptoHelper.Encrypt(siteToSave.DisplayName);
+ }
+
+ if (siteToSave.Id == 0)
+ {
+ siteToSave.CreateTime = DateTime.Now;
+ siteToSave.UpdateTime = DateTime.Now;
+ context.SiteItems.Add(siteToSave);
+ }
+ else
+ {
+ var existingSite = context.SiteItems.Find(siteToSave.Id);
+ if (existingSite != null)
+ {
+ context.Entry(existingSite).CurrentValues.SetValues(siteToSave);
+ existingSite.UpdateTime = DateTime.Now;
+ }
+ }
+ context.SaveChanges();
+ OnDataChanged(); // 触发数据变更事件
+ }
+ }
+
+ ///
+ /// 删除指定ID的分组
+ ///
+ /// 要删除的分组ID
+ public static void DeleteGroup(int groupId)
+ {
+ using (var context = new AppDbContext())
+ {
+ var group = context.SiteGroups.Find(groupId);
+ if (group != null)
+ {
+ context.SiteGroups.Remove(group);
+ context.SaveChanges();
+ OnDataChanged(); // 触发数据变更事件
+ }
+ }
+ }
+
+ ///
+ /// 删除指定ID的网站
+ ///
+ /// 要删除的网站ID
+ public static void DeleteSite(int siteId)
+ {
+ using (var context = new AppDbContext())
+ {
+ var site = context.SiteItems.Find(siteId);
+ if (site != null)
+ {
+ context.SiteItems.Remove(site);
+ context.SaveChanges();
+ OnDataChanged(); // 触发数据变更事件
+ }
+ }
+ }
+
+ ///
+ /// 更新网站的访问信息
+ ///
+ /// 要更新的网站ID
+ public static void UpdateSiteAccess(int siteId)
+ {
+ using (var context = new AppDbContext())
+ {
+ var site = context.SiteItems.Find(siteId);
+ if (site != null)
+ {
+ site.LastAccessTime = DateTime.Now;
+ site.AccessCount++;
+ context.SaveChanges();
+ }
+ }
+ }
+
+ ///
+ /// 获取所有分组(包括未启用的)
+ ///
+ /// 所有分组的列表
+ public static List GetAllGroups()
+ {
+ try
+ {
+ using (var context = new AppDbContext())
+ {
+ // 检查数据库连接
+ System.Diagnostics.Debug.WriteLine($"数据库路径: {DatabaseInitializer.GetDbPath()}");
+
+ // 检查是否有任何分组
+ var groupCount = context.SiteGroups.Count();
+
+ // 先获取所有分组,不使用Include
+ var groups = context.SiteGroups
+ .OrderBy(g => g.SortOrder)
+ .ThenBy(g => g.Name)
+ .ToList();
+
+ // 手动加载每个分组的站点并解密
+ foreach (var group in groups)
+ {
+ try
+ {
+ // 确保IsDefaultExpanded有有效值
+ if (group.IsDefaultExpanded != true && group.IsDefaultExpanded != false)
+ {
+ System.Diagnostics.Debug.WriteLine($"警告:分组 {group.Name} (ID: {group.Id}) 的IsDefaultExpanded值无效,设置为默认值false");
+ group.IsDefaultExpanded = false;
+ }
+
+ // 获取站点数据
+ var sites = context.SiteItems
+ .Where(s => s.GroupId == group.Id)
+ .OrderBy(s => s.SortOrder)
+ .ToList();
+
+
+ // 检查每个站点的数据
+ foreach (var site in sites)
+ {
+ try
+ {
+
+ // 确保所有必需字段都有有效值
+ if (string.IsNullOrEmpty(site.DisplayName))
+ {
+ System.Diagnostics.Debug.WriteLine($"警告:站点 ID={site.Id} 的DisplayName为空");
+ site.DisplayName = "未命名站点";
+ }
+ if (string.IsNullOrEmpty(site.Url))
+ {
+ System.Diagnostics.Debug.WriteLine($"警告:站点 ID={site.Id} 的Url为空");
+ site.Url = "about:blank";
+ }
+ }
+ catch (Exception ex)
+ {
+ System.Diagnostics.Debug.WriteLine($"处理站点 ID={site.Id} 时出错: {ex}");
+ }
+ }
+
+ group.Sites = sites;
+
+ // 解密站点敏感信息
+ if (group.Sites != null)
+ {
+ try
+ {
+ DecryptSiteInfoBatch(group.Sites);
+ }
+ catch (Exception ex)
+ {
+ System.Diagnostics.Debug.WriteLine($"解密分组 {group.Name} 的站点信息时出错: {ex}");
+ }
+ }
+
+ }
+ catch (Exception ex)
+ {
+ System.Diagnostics.Debug.WriteLine($"处理分组 {group.Name} (ID: {group.Id}) 时出错: {ex}");
+ throw;
+ }
+ }
+
+ return groups;
+ }
+ }
+ catch (Exception ex)
+ {
+ System.Diagnostics.Debug.WriteLine($"获取分组时出错: {ex}");
+ throw;
+ }
+ }
+
+ ///
+ /// 获取所有网站(包括未启用的)
+ ///
+ /// 所有网站的列表
+ public static List GetAllSites()
+ {
+ using (var context = new AppDbContext())
+ {
+ var sites = context.SiteItems
+ .OrderBy(s => s.SortOrder)
+ .ThenBy(s => s.DisplayName)
+ .ToList();
+
+ // 解密敏感信息
+ DecryptSiteInfoBatch(sites);
+
+ return sites;
+ }
+ }
+
+ ///
+ /// 初始化数据库
+ ///
+ public static void InitializeDatabase()
+ {
+ DatabaseInitializer.Initialize();
+ }
+
+ ///
+ /// 添加分组
+ ///
+ /// 要添加的分组
+ public static void AddGroup(SiteGroup group)
+ {
+ using (var context = new AppDbContext())
+ {
+ context.SiteGroups.Add(group);
+ context.SaveChanges();
+ OnDataChanged(); // 触发数据变更事件
+ }
+ }
+
+ ///
+ /// 更新分组
+ ///
+ /// 要更新的分组
+ public static void UpdateGroup(SiteGroup group)
+ {
+ using (var context = new AppDbContext())
+ {
+ context.SiteGroups.Update(group);
+ context.SaveChanges();
+ OnDataChanged(); // 触发数据变更事件
+ }
+ }
+
+ ///
+ /// 添加网站
+ ///
+ /// 要添加的网站
+ public static void AddSite(SiteItem site)
+ {
+ using (var context = new AppDbContext())
+ {
+ // 创建副本并加密敏感信息
+ var siteToAdd = new SiteItem
+ {
+ GroupId = site.GroupId,
+ DisplayName = !string.IsNullOrEmpty(site.DisplayName) ? CryptoHelper.Encrypt(site.DisplayName) : site.DisplayName,
+ Username = !string.IsNullOrEmpty(site.Username) ? CryptoHelper.Encrypt(site.Username) : site.Username,
+ Password = !string.IsNullOrEmpty(site.Password) ? CryptoHelper.Encrypt(site.Password) : site.Password,
+ CommonUsername = !string.IsNullOrEmpty(site.CommonUsername) ? CryptoHelper.Encrypt(site.CommonUsername) : site.CommonUsername,
+ CommonPassword = !string.IsNullOrEmpty(site.CommonPassword) ? CryptoHelper.Encrypt(site.CommonPassword) : site.CommonPassword,
+ GoogleSecret = !string.IsNullOrEmpty(site.GoogleSecret) ? CryptoHelper.Encrypt(site.GoogleSecret) : site.GoogleSecret,
+ Url = !string.IsNullOrEmpty(site.Url) ? CryptoHelper.Encrypt(site.Url) : site.Url,
+ IsEnabled = site.IsEnabled,
+ SortOrder = site.SortOrder,
+ CreateTime = DateTime.Now,
+ UpdateTime = DateTime.Now,
+ LastAccessTime = site.LastAccessTime,
+ AccessCount = site.AccessCount
+ };
+
+ context.SiteItems.Add(siteToAdd);
+ context.SaveChanges();
+ OnDataChanged(); // 触发数据变更事件
+ }
+ }
+
+ ///
+ /// 更新网站
+ ///
+ /// 要更新的网站
+ public static void UpdateSite(SiteItem site)
+ {
+ using (var context = new AppDbContext())
+ {
+ var existingSite = context.SiteItems.Find(site.Id);
+ if (existingSite != null)
+ {
+ // 更新非敏感字段
+ existingSite.GroupId = site.GroupId;
+ //existingSite.DisplayName = site.DisplayName;
+ existingSite.IsEnabled = site.IsEnabled;
+ existingSite.SortOrder = site.SortOrder;
+ existingSite.UpdateTime = DateTime.Now;
+ existingSite.LastAccessTime = site.LastAccessTime;
+ existingSite.AccessCount = site.AccessCount;
+
+ // 加密并更新敏感字段
+ existingSite.Username = !string.IsNullOrEmpty(site.Username) ? CryptoHelper.Encrypt(site.Username) : site.Username;
+ existingSite.Password = !string.IsNullOrEmpty(site.Password) ? CryptoHelper.Encrypt(site.Password) : site.Password;
+ existingSite.CommonUsername = !string.IsNullOrEmpty(site.CommonUsername) ? CryptoHelper.Encrypt(site.CommonUsername) : site.CommonUsername;
+ existingSite.CommonPassword = !string.IsNullOrEmpty(site.CommonPassword) ? CryptoHelper.Encrypt(site.CommonPassword) : site.CommonPassword;
+ existingSite.GoogleSecret = !string.IsNullOrEmpty(site.GoogleSecret) ? CryptoHelper.Encrypt(site.GoogleSecret) : site.GoogleSecret;
+ existingSite.Url = !string.IsNullOrEmpty(site.Url) ? CryptoHelper.Encrypt(site.Url) : site.Url;
+ existingSite.DisplayName = !string.IsNullOrEmpty(site.DisplayName) ? CryptoHelper.Encrypt(site.DisplayName) : site.DisplayName;
+
+ context.SaveChanges();
+ OnDataChanged(); // 触发数据变更事件
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/csharp/BrowserTool/BrowserTool/GroupEditDialog.xaml b/csharp/BrowserTool/BrowserTool/GroupEditDialog.xaml
new file mode 100644
index 0000000000000000000000000000000000000000..e5e557a594c4aa9c46e74a669b53824f23ab1149
--- /dev/null
+++ b/csharp/BrowserTool/BrowserTool/GroupEditDialog.xaml
@@ -0,0 +1,122 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/csharp/BrowserTool/BrowserTool/GroupEditDialog.xaml.cs b/csharp/BrowserTool/BrowserTool/GroupEditDialog.xaml.cs
new file mode 100644
index 0000000000000000000000000000000000000000..728a0bdf70950ce7141e1e5bb516e91c3ac726ce
--- /dev/null
+++ b/csharp/BrowserTool/BrowserTool/GroupEditDialog.xaml.cs
@@ -0,0 +1,44 @@
+using System.Windows;
+
+namespace BrowserTool
+{
+ public partial class GroupEditDialog : Window
+ {
+ public string GroupName { get; set; }
+ public bool IsDefaultExpanded { get; set; }
+
+ public GroupEditDialog()
+ {
+ InitializeComponent();
+ DataContext = this;
+ }
+
+ public GroupEditDialog(string groupName, bool isDefaultExpanded = false) : this()
+ {
+ GroupName = groupName;
+ IsDefaultExpanded = isDefaultExpanded;
+ chkDefaultExpanded.IsChecked = isDefaultExpanded;
+ }
+
+ private void btnOK_Click(object sender, RoutedEventArgs e)
+ {
+ if (string.IsNullOrWhiteSpace(GroupName))
+ {
+ MessageBox.Show("请输入分组名称", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
+ return;
+ }
+
+ // 更新IsDefaultExpanded属性
+ IsDefaultExpanded = chkDefaultExpanded.IsChecked ?? false;
+
+ DialogResult = true;
+ Close();
+ }
+
+ private void btnCancel_Click(object sender, RoutedEventArgs e)
+ {
+ DialogResult = false;
+ Close();
+ }
+ }
+}
\ No newline at end of file
diff --git a/csharp/BrowserTool/BrowserTool/IsTreeViewRootConverter.cs b/csharp/BrowserTool/BrowserTool/IsTreeViewRootConverter.cs
new file mode 100644
index 0000000000000000000000000000000000000000..1659c1d16d09c7c661d1021d416f5b757a009915
--- /dev/null
+++ b/csharp/BrowserTool/BrowserTool/IsTreeViewRootConverter.cs
@@ -0,0 +1,34 @@
+using System;
+using System.Globalization;
+using System.Windows.Data;
+using System.Windows.Controls;
+using System.Windows;
+
+namespace BrowserTool
+{
+ public class IsTreeViewRootConverter : IValueConverter
+ {
+ public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+ {
+ var tvi = value as TreeViewItem;
+ if (tvi == null)
+ return System.Windows.Visibility.Collapsed;
+ var parent = System.Windows.Media.VisualTreeHelper.GetParent(tvi);
+ while (parent != null && !(parent is TreeViewItem) && !(parent is System.Windows.Controls.TreeView))
+ {
+ parent = System.Windows.Media.VisualTreeHelper.GetParent(parent);
+ }
+ if (parent is System.Windows.Controls.TreeView)
+ {
+ // 只有父级为TreeView才是根节点
+ return System.Windows.Visibility.Visible;
+ }
+ return System.Windows.Visibility.Collapsed;
+ }
+
+ public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+ {
+ throw new NotImplementedException();
+ }
+ }
+}
\ No newline at end of file
diff --git a/csharp/BrowserTool/BrowserTool/LoginWindow.xaml b/csharp/BrowserTool/BrowserTool/LoginWindow.xaml
new file mode 100644
index 0000000000000000000000000000000000000000..4347d8826edac512f60396c68f552c836f279f65
--- /dev/null
+++ b/csharp/BrowserTool/BrowserTool/LoginWindow.xaml
@@ -0,0 +1,107 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/csharp/BrowserTool/BrowserTool/LoginWindow.xaml.cs b/csharp/BrowserTool/BrowserTool/LoginWindow.xaml.cs
new file mode 100644
index 0000000000000000000000000000000000000000..08eee5e87e67eabf3d0d5a586ad8ec769dc0d6d9
--- /dev/null
+++ b/csharp/BrowserTool/BrowserTool/LoginWindow.xaml.cs
@@ -0,0 +1,66 @@
+using System.Windows;
+using System.Windows.Input;
+using BrowserTool.Utils;
+
+namespace BrowserTool
+{
+ public partial class LoginWindow : Window
+ {
+ private const string DEFAULT_PASSWORD = "qwe123";
+
+ public LoginWindow()
+ {
+ InitializeComponent();
+ txtPassword.Focus();
+ }
+
+ private void btnOK_Click(object sender, RoutedEventArgs e)
+ {
+ ValidatePassword();
+ }
+
+ private void btnCancel_Click(object sender, RoutedEventArgs e)
+ {
+ DialogResult = false;
+ Close();
+ }
+
+ private void txtPassword_KeyDown(object sender, KeyEventArgs e)
+ {
+ if (e.Key == Key.Enter)
+ {
+ ValidatePassword();
+ }
+ }
+
+ private void ValidatePassword()
+ {
+ string password = txtPassword.Password;
+
+ if (string.IsNullOrWhiteSpace(password))
+ {
+ ShowError("密码不能为空!");
+ return;
+ }
+
+ if (PasswordHelper.VerifyOrSetStartupPassword(password))
+ {
+ KeyManager.SetPassword(password);
+ DialogResult = true;
+ Close();
+ }
+ else
+ {
+ ShowError("密码错误!");
+ txtPassword.Password = string.Empty;
+ txtPassword.Focus();
+ }
+ }
+
+ private void ShowError(string message)
+ {
+ txtError.Text = message;
+ txtError.Visibility = Visibility.Visible;
+ }
+ }
+}
\ No newline at end of file
diff --git a/csharp/BrowserTool/BrowserTool/MainWindow.xaml b/csharp/BrowserTool/BrowserTool/MainWindow.xaml
new file mode 100644
index 0000000000000000000000000000000000000000..0143e4c573aa7a989f8a0dfbcbf7079f13503b5f
--- /dev/null
+++ b/csharp/BrowserTool/BrowserTool/MainWindow.xaml
@@ -0,0 +1,916 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/csharp/BrowserTool/BrowserTool/MainWindow.xaml.cs b/csharp/BrowserTool/BrowserTool/MainWindow.xaml.cs
new file mode 100644
index 0000000000000000000000000000000000000000..f7bbf9abf890fc2adbb2d02b407aec77d6415fe0
--- /dev/null
+++ b/csharp/BrowserTool/BrowserTool/MainWindow.xaml.cs
@@ -0,0 +1,2413 @@
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ComponentModel;
+using System.Configuration;
+using System.Diagnostics;
+using System.IO;
+using System.Linq;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Security.Policy;
+using System.Text;
+using System.Text.RegularExpressions;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Controls.Primitives;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Interop;
+using System.Windows.Media;
+using System.Windows.Media.Animation;
+using System.Windows.Media.Imaging;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+using System.Windows.Threading;
+using BrowserTool.Browser;
+using BrowserTool.Database;
+using BrowserTool.Database.Entities;
+using BrowserTool.Utils;
+using CefSharp;
+using CefSharp.Wpf;
+using Hardcodet.Wpf.TaskbarNotification;
+using NLog;
+
+namespace BrowserTool;
+
+///
+/// 标签页信息类,用于存储标签页的URL和ID
+///
+public sealed record TabInfo
+{
+ ///
+ /// 获取或设置当前URL
+ ///
+ public string Url { get; set; } = string.Empty;
+
+ ///
+ /// 获取或设置标签页唯一标识符
+ ///
+ public string TabId { get; set; } = string.Empty;
+
+ ///
+ /// 获取或设置原始URL,用于标识标签页来源的菜单项
+ ///
+ public string OriginalUrl { get; set; } = string.Empty;
+
+ ///
+ /// 获取或设置菜单项ID,用于唯一标识来源的二级菜单
+ ///
+ public int? MenuItemId { get; set; }
+
+ ///
+ /// 获取或设置菜单项标题,用于显示和调试
+ ///
+ public string MenuItemTitle { get; set; } = string.Empty;
+}
+
+///
+/// MainWindow.xaml 的交互逻辑类
+///
+public partial class MainWindow : Window
+{
+ #region 嵌套类型定义
+
+ ///
+ /// 菜单组数据结构
+ ///
+ public sealed record MenuGroup
+ {
+ ///
+ /// 获取或设置组名称
+ ///
+ public string GroupName { get; set; } = string.Empty;
+
+ ///
+ /// 获取或设置是否默认展开
+ ///
+ public bool IsDefaultExpanded { get; set; }
+
+ ///
+ /// 获取或设置菜单项列表
+ ///
+ public List Items { get; set; } = new();
+ }
+
+ ///
+ /// 菜单项数据结构
+ ///
+ public sealed record MenuItemData
+ {
+ ///
+ /// 获取或设置菜单项的数据库ID
+ ///
+ public int Id { get; set; }
+
+ ///
+ /// 获取或设置菜单项名称
+ ///
+ public string Name { get; set; } = string.Empty;
+
+ ///
+ /// 获取或设置菜单项URL
+ ///
+ public string Url { get; set; } = string.Empty;
+
+ ///
+ /// 获取或设置菜单项图标
+ ///
+ public string Icon { get; set; } = string.Empty;
+ }
+
+ ///
+ /// 浏览器上下文类,实现属性变更通知
+ ///
+ public sealed class BrowserContext : INotifyPropertyChanged
+ {
+ private bool _isLoading;
+
+ ///
+ /// 获取或设置是否正在加载
+ ///
+ public bool IsLoading
+ {
+ get => _isLoading;
+ set
+ {
+ if (_isLoading != value)
+ {
+ _isLoading = value;
+ PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsLoading)));
+ }
+ }
+ }
+
+ ///
+ /// 属性变更通知事件
+ ///
+ public event PropertyChangedEventHandler? PropertyChanged;
+ }
+
+
+
+ #endregion
+
+ #region 字段和属性
+
+ ///
+ /// 菜单数据集合
+ ///
+ private readonly List _menuGroups = new();
+
+ ///
+ /// 抽屉是否打开
+ ///
+ private bool _isDrawerOpen = true;
+
+ ///
+ /// 最后的窗口状态
+ ///
+ private WindowState _lastWindowState = WindowState.Normal;
+
+ ///
+ /// 恢复边界
+ ///
+ private Rect _restoreBounds;
+
+ ///
+ /// 日志记录器
+ ///
+ private static readonly Logger _logger = LogManager.GetCurrentClassLogger();
+
+ ///
+ /// Windows消息常量
+ ///
+ private static readonly int WM_SHOWMAINWINDOW = RegisterWindowMessage("BrowserTool_ShowMainWindow");
+
+ ///
+ /// 获取抽屉是否打开状态
+ ///
+ public bool IsDrawerOpen => _isDrawerOpen;
+
+ #endregion
+
+ #region Windows API 声明
+
+ ///
+ /// 注册自定义Windows消息
+ ///
+ /// 消息字符串
+ /// 消息ID
+ [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
+ private static extern int RegisterWindowMessage(string lpString);
+
+ #endregion
+
+ #region 构造函数
+
+ ///
+ /// 初始化MainWindow的新实例
+ ///
+ public MainWindow()
+ {
+ try
+ {
+ InitializeComponent();
+ InitializeMainWindow();
+ }
+ catch (Exception ex)
+ {
+ _logger.Error("初始化主窗口时发生异常", ex);
+ Application.Current.Shutdown();
+ }
+ }
+
+ ///
+ /// 初始化主窗口设置
+ ///
+ private void InitializeMainWindow()
+ {
+ // 监听标签页切换
+ MainTabControl.SelectionChanged += MainTabControl_SelectionChanged;
+
+ // 窗口居中显示
+ WindowStartupLocation = WindowStartupLocation.CenterScreen;
+
+ // 订阅数据变更事件
+ SiteConfig.DataChanged += OnDataChanged;
+
+ // 添加Windows消息处理
+ SourceInitialized += MainWindow_SourceInitialized;
+
+ // 订阅登录状态变化事件
+ LoginManager.OnLoginStatusChanged += OnLoginStatusChanged;
+
+ // 设置ContextMenu的PlacementTarget
+ TabContextMenu.Opened += (s, e) =>
+ {
+ if (TabContextMenu.PlacementTarget == null)
+ {
+ TabContextMenu.PlacementTarget = MainTabControl;
+ }
+ };
+
+ // 根据配置控制手动打卡按钮的显示
+ bool showManualCheckInButton = true;
+ if (bool.TryParse(ConfigurationManager.AppSettings["ShowManualCheckInButton"], out bool configValue))
+ {
+ showManualCheckInButton = configValue;
+ }
+ ManualCheckInButton.Visibility = showManualCheckInButton ? Visibility.Visible : Visibility.Collapsed;
+ }
+
+ #endregion
+
+ #region Windows 消息处理
+
+ ///
+ /// 窗口源初始化事件处理器
+ ///
+ private void MainWindow_SourceInitialized(object sender, EventArgs e)
+ {
+ var source = HwndSource.FromHwnd(new WindowInteropHelper(this).Handle);
+ source.AddHook(WndProc);
+ }
+
+ ///
+ /// Windows消息处理程序
+ ///
+ /// 窗口句柄
+ /// 消息类型
+ /// 消息参数
+ /// 消息参数
+ /// 是否已处理
+ /// 处理结果
+ private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
+ {
+ if (msg == WM_SHOWMAINWINDOW)
+ {
+ _logger.Debug($"收到WM_SHOWMAINWINDOW消息: {msg}");
+
+ Dispatcher.BeginInvoke(new Action(() =>
+ {
+ var app = App.GetCurrentApp();
+ if (app is not null)
+ {
+ _logger.Debug("调用App.ShowMainWindow");
+ app.ShowMainWindow();
+ }
+ else
+ {
+ _logger.Debug("App实例为null");
+ }
+ }));
+
+ handled = true;
+ }
+
+ return IntPtr.Zero;
+ }
+
+ #endregion
+
+ #region 数据变更处理
+
+ ///
+ /// 数据变更事件处理器
+ ///
+ private void OnDataChanged(object sender, EventArgs e) =>
+ Dispatcher.Invoke(LoadMenuGroupsFromDb);
+
+ ///
+ /// 登录状态变化事件处理器
+ ///
+ /// 是否已登录
+ private void OnLoginStatusChanged(bool isLoggedIn)
+ {
+ Dispatcher.BeginInvoke(new Action(() =>
+ {
+ if (isLoggedIn)
+ {
+ RefreshMenuFromSettings();
+ }
+ }));
+ }
+
+ #endregion
+
+ #region 资源清理
+
+ ///
+ /// 窗口关闭时的清理工作
+ ///
+ protected override void OnClosed(EventArgs e)
+ {
+ base.OnClosed(e);
+ SiteConfig.DataChanged -= OnDataChanged;
+ }
+
+ #endregion
+
+ #region 菜单管理
+
+ ///
+ /// 从数据库加载菜单组数据
+ ///
+ private void LoadMenuGroupsFromDb()
+ {
+ try
+ {
+ SiteConfig.InitializeDatabase();
+ var allGroups = SiteConfig.GetAllGroups();
+
+ _logger.Debug($"加载到 {allGroups.Count} 个分组");
+
+ _menuGroups.Clear();
+ _menuGroups.AddRange(allGroups.Select(g => new MenuGroup
+ {
+ GroupName = g.Name,
+ IsDefaultExpanded = g.IsDefaultExpanded,
+ Items = g.Sites
+ .Where(s => s.IsEnabled)
+ .OrderBy(s => s.SortOrder)
+ .Select(s => new MenuItemData
+ {
+ Id = s.Id,
+ Name = s.DisplayName,
+ Url = s.Url,
+ Icon = s.Icon
+ }).ToList()
+ }));
+
+ RefreshMenuTreeUI();
+ }
+ catch (Exception ex)
+ {
+ _logger.Error("加载菜单数据时出错", ex);
+ MessageBox.Show($"加载菜单数据时出错:{ex.Message}", "错误",
+ MessageBoxButton.OK, MessageBoxImage.Error);
+ }
+ }
+
+ ///
+ /// 刷新菜单树UI
+ ///
+ private void RefreshMenuTreeUI()
+ {
+ if (MenuTree is null)
+ {
+ return;
+ }
+
+ MenuTree.Items.Clear();
+
+ foreach (var group in _menuGroups)
+ {
+ var groupItem = new TreeViewItem
+ {
+ Header = group.GroupName,
+ IsExpanded = group.IsDefaultExpanded
+ };
+
+ foreach (var item in group.Items)
+ {
+ var stackPanel = CreateMenuItemPanel(item);
+ var subItem = new TreeViewItem { Header = stackPanel, Tag = item };
+ groupItem.Items.Add(subItem);
+ }
+
+ MenuTree.Items.Add(groupItem);
+ }
+
+ _logger.Debug($"UI 更新完成,共添加 {MenuTree.Items.Count} 个分组");
+ }
+
+ ///
+ /// 创建菜单项面板
+ ///
+ /// 菜单项数据
+ /// 菜单项面板
+ private StackPanel CreateMenuItemPanel(MenuItemData item)
+ {
+ var stackPanel = new StackPanel { Orientation = Orientation.Horizontal };
+
+ if (!string.IsNullOrEmpty(item.Icon))
+ {
+ var image = CreateMenuItemIcon(item.Icon);
+ if (image is not null)
+ {
+ stackPanel.Children.Add(image);
+ }
+ }
+
+ var textBlock = new TextBlock
+ {
+ Text = item.Name,
+ VerticalAlignment = VerticalAlignment.Center,
+ Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#CCCCCC"))
+ };
+
+ stackPanel.Children.Add(textBlock);
+ return stackPanel;
+ }
+
+ ///
+ /// 创建菜单项图标
+ ///
+ /// 图标路径
+ /// 图像控件,如果创建失败则返回null
+ private Image? CreateMenuItemIcon(string iconPath)
+ {
+ try
+ {
+ var image = new Image
+ {
+ Width = 16,
+ Height = 16,
+ Margin = new Thickness(0, 0, 5, 0)
+ };
+
+ var bitmap = Utils.ImageCache.GetImage(iconPath);
+ if (bitmap is not null)
+ {
+ image.Source = bitmap;
+ return image;
+ }
+ }
+ catch (Exception ex)
+ {
+ _logger.Error("加载图标时出错", ex);
+ }
+
+ return null;
+ }
+
+ ///
+ /// 初始化左侧菜单树,支持可选过滤
+ ///
+ /// 过滤条件
+ private void InitMenuTree(string filter = "")
+ {
+ MenuTree.Items.Clear();
+
+ foreach (var group in _menuGroups)
+ {
+ var filteredItems = string.IsNullOrWhiteSpace(filter)
+ ? group.Items
+ : group.Items.Where(i => i.Name.Contains(filter, StringComparison.OrdinalIgnoreCase)).ToList();
+
+ if (filteredItems.Count == 0 && !string.IsNullOrWhiteSpace(filter))
+ {
+ continue;
+ }
+
+ var groupItem = new TreeViewItem
+ {
+ Header = group.GroupName,
+ IsExpanded = group.IsDefaultExpanded
+ };
+
+ foreach (var item in filteredItems)
+ {
+ var stackPanel = CreateMenuItemPanel(item);
+ var subItem = new TreeViewItem { Header = stackPanel, Tag = item };
+ groupItem.Items.Add(subItem);
+ }
+
+ MenuTree.Items.Add(groupItem);
+ }
+ }
+
+ ///
+ /// 刷新主窗口菜单,可以被设置窗口直接调用
+ ///
+ public void RefreshMenuFromSettings()
+ {
+ Dispatcher.BeginInvoke(new Action(() =>
+ {
+ try
+ {
+ _logger.Debug("[MainWindow.RefreshMenuFromSettings] 开始重新加载菜单");
+ LoadMenuGroupsFromDb();
+ MenuTree.Items.Refresh();
+ _logger.Debug("[MainWindow.RefreshMenuFromSettings] 菜单刷新完成");
+ }
+ catch (Exception ex)
+ {
+ _logger.Error("[MainWindow.RefreshMenuFromSettings] 刷新菜单时出错", ex);
+ MessageBox.Show($"刷新菜单时出错:{ex.Message}", "错误",
+ MessageBoxButton.OK, MessageBoxImage.Error);
+ }
+ }), DispatcherPriority.Render);
+ }
+
+ #endregion
+
+ #region 搜索功能
+
+ ///
+ /// 搜索框文本变更事件处理器
+ ///
+ private void SearchBox_TextChanged(object sender, TextChangedEventArgs e) =>
+ InitMenuTree(SearchBox.Text.Trim());
+
+ #endregion
+
+ #region 菜单事件处理
+
+ ///
+ /// 菜单项选择变更事件处理器
+ ///
+ private void MenuTree_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs