diff --git a/src/App.xaml.cs b/src/App.xaml.cs index ec6c813..b6870b0 100644 --- a/src/App.xaml.cs +++ b/src/App.xaml.cs @@ -75,11 +75,11 @@ protected override void OnStartup(StartupEventArgs e) RestartWithAdminPrivileges(e.Args); return; } - catch (Exception ex) - { - AppLogger.Error("Restart with admin privileges failed.", ex); - Debug.WriteLine("自动请求管理员权限被拒绝或失败: " + ex.Message); - } + catch (Exception ex) + { + AppLogger.Error("Restart with admin privileges failed.", ex); + Debug.WriteLine("自动请求管理员权限被拒绝或失败: " + ex.Message); + } } SystemEvents.SessionEnding += OnSessionEnding; @@ -128,7 +128,7 @@ private bool IsRunningAsAdmin() private void RestartWithAdminPrivileges(string[] args) { - string exePath = System.Environment.ProcessPath ?? + string exePath = System.Environment.ProcessPath ?? System.Diagnostics.Process.GetCurrentProcess().MainModule!.FileName; ProcessStartInfo startInfo = new ProcessStartInfo @@ -232,7 +232,7 @@ private void RestartApplication() { try { - string exePath = System.Environment.ProcessPath ?? + string exePath = System.Environment.ProcessPath ?? System.Diagnostics.Process.GetCurrentProcess().MainModule!.FileName; ProcessStartInfo startInfo = new ProcessStartInfo(exePath) { UseShellExecute = true }; @@ -269,13 +269,13 @@ private void ExitApplication() this.Dispatcher.Invoke(() => { - try { _controlPanel?.Close(); } catch { } - try { Overlay?.Dispose(); } catch { } + try { _controlPanel?.Close(); } catch { /* ignore: best-effort cleanup during shutdown */ } + try { Overlay?.Dispose(); } catch { /* ignore: best-effort cleanup during shutdown */ } }); if (_mutex != null) { - try { _mutex.ReleaseMutex(); } catch { } + try { _mutex.ReleaseMutex(); } catch { /* ignore: mutex disposal during shutdown */ } _mutex.Dispose(); _mutex = null; } diff --git a/src/ConfigManager.cs b/src/ConfigManager.cs index 3e07275..e06e66d 100644 --- a/src/ConfigManager.cs +++ b/src/ConfigManager.cs @@ -151,7 +151,11 @@ public static void Load() { _profiles = System.Text.Json.JsonSerializer.Deserialize>(FilterProfiles) ?? new List(); } - catch { _profiles = new List(); } + catch (Exception ex) + { + AppLogger.Warn($"Failed to deserialize FilterProfiles; fallback to empty list: {ex.Message}"); + _profiles = new List(); + } } // 向后兼容处理 @@ -187,7 +191,10 @@ public static void Load() } } } - catch { } + catch (Exception ex) + { + AppLogger.Warn($"Failed to load config; some values may be missing: {ex.Message}"); + } } public static PanelScrollbarVisibility ParseScrollbarVisibility(string? raw) @@ -327,7 +334,10 @@ public static void Save(string name, object value) } } } - catch { } + catch (Exception ex) + { + AppLogger.Warn($"Failed to save config entry '{name}': {ex.Message}"); + } } public static IReadOnlySet GetProcessFilterEntries() @@ -353,8 +363,9 @@ public static HashSet GetEnabledScreenIds() .Select(s => s.Trim()) .ToHashSet(StringComparer.OrdinalIgnoreCase); } - catch + catch (Exception ex) { + AppLogger.Warn($"Failed to parse EnabledScreenIds; fallback to empty set: {ex.Message}"); return new HashSet(StringComparer.OrdinalIgnoreCase); } } @@ -382,8 +393,9 @@ public static List GetScreenSelections() { return System.Text.Json.JsonSerializer.Deserialize>(ScreenSelections) ?? new List(); } - catch + catch (Exception ex) { + AppLogger.Warn($"Failed to parse ScreenSelections; fallback to empty list: {ex.Message}"); return new List(); } } @@ -518,7 +530,10 @@ public static void ResetAndClear() TelemetryClientId = ""; LastTelemetrySentUtc = ""; } - catch { } + catch (Exception ex) + { + AppLogger.Warn($"Failed to reset config; registry/data may be partially cleared: {ex.Message}"); + } } } } diff --git a/src/ControlPanelWindow.xaml.cs b/src/ControlPanelWindow.xaml.cs index dbbaafc..10b979c 100644 --- a/src/ControlPanelWindow.xaml.cs +++ b/src/ControlPanelWindow.xaml.cs @@ -511,7 +511,7 @@ private void RefreshRunningProcessList() } } } - catch (Exception ex) { Debug.WriteLine(ex.Message); } + catch (Exception ex) { AppLogger.Warn($"Failed to enumerate running processes: {ex.Message}"); } } private void SearchRunningProcess_TextChanged(object sender, TextChangedEventArgs e) @@ -561,7 +561,7 @@ private void LoadSettingsCore() CheckEnvironmentFilter.IsChecked = ConfigManager.EnableEnvironmentFilter; CheckHideInFullscreen.IsChecked = ConfigManager.HideInFullscreen; CheckShowEffectOnDesktop.IsChecked = ConfigManager.ShowEffectOnDesktop; - CheckRunAsAdmin.IsChecked = ConfigManager.RunAsAdmin; + CheckRunAsAdmin.IsChecked = ConfigManager.RunAsAdmin; CheckTouchscreenMode.IsChecked = ConfigManager.IsTouchscreenMode; CheckMiddleClickTrigger.IsChecked = ConfigManager.EnableMiddleClickTrigger; CheckScreenshotCompatibilityMode.IsChecked = ConfigManager.ScreenshotCompatibilityMode; @@ -816,7 +816,7 @@ private void UpdateEnvironmentFilterInterlock() CheckShowEffectOnDesktop.IsEnabled = environmentFilterEnabled; ComboProfiles.IsEnabled = environmentFilterEnabled; ComboProcessFilterMode.IsEnabled = environmentFilterEnabled; - + if (ListConfiguredProcesses != null) { ListConfiguredProcesses.IsEnabled = processFilterEnabled; @@ -966,7 +966,7 @@ private void PickColor_Click(object sender, RoutedEventArgs e) dialog.Color = System.Drawing.Color.FromArgb( byte.Parse(parts[0]), byte.Parse(parts[1]), byte.Parse(parts[2])); } - catch { } + catch { /* ignore: fallback to default color */ } if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { @@ -1115,7 +1115,7 @@ private void RenameProfile_Click(object sender, RoutedEventArgs e) private void ConfirmRenameProfile_Click(object sender, RoutedEventArgs e) { string newName = NewProfileNameInput.Text.Trim(); - + if (!string.IsNullOrWhiteSpace(newName) && ComboProfiles.SelectedItem is FilterProfile active) { active.Name = newName; @@ -1389,7 +1389,7 @@ private void SaveSettings_Click(object sender, RoutedEventArgs e) bool telemetryEnabled = CheckTelemetry.IsChecked ?? false; bool telemetryWasEnabled = ConfigManager.EnableTelemetry; - + // 保存配置组 string activeId = (ComboProfiles.SelectedItem as FilterProfile)?.Id ?? ""; ConfigManager.SaveProfiles(Profiles.ToList(), activeId); @@ -1498,7 +1498,7 @@ private void SaveSettings_Click(object sender, RoutedEventArgs e) Localization.Get("Msg_AdminRestart_Title"), MessageBoxButton.YesNo, MessageBoxImage.Question); - + if (res == MessageBoxResult.Yes) { RestartAsAdmin(); @@ -1582,7 +1582,7 @@ private void ApplyAutoStartSettings() { bool autoStart = CheckAutoStart.IsChecked == true; bool runAsAdmin = CheckRunAsAdmin.IsChecked == true; - + string? exePath = AutoStartManager.ResolveExecutablePath( Environment.ProcessPath, Process.GetCurrentProcess().MainModule?.FileName, @@ -1593,7 +1593,7 @@ private void ApplyAutoStartSettings() string regKeyPath = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run"; AutoStartPlan plan = AutoStartManager.CreatePlan(autoStart, runAsAdmin); - + try { using (RegistryKey? key = Registry.CurrentUser.CreateSubKey(regKeyPath, true)) @@ -1620,8 +1620,8 @@ private void ManageTaskScheduler(string taskName, string exePath, bool create) { try { - string arguments = create - ? $"/create /tn \"{taskName}\" /tr \"\\\"{exePath}\\\" --autostart\" /sc onlogon /rl highest /f" + string arguments = create + ? $"/create /tn \"{taskName}\" /tr \"\\\"{exePath}\\\" --autostart\" /sc onlogon /rl highest /f" : $"/delete /tn \"{taskName}\" /f"; ProcessStartInfo startInfo = new ProcessStartInfo @@ -1633,7 +1633,7 @@ private void ManageTaskScheduler(string taskName, string exePath, bool create) WindowStyle = ProcessWindowStyle.Hidden, Verb = new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator) ? "" : "runas" }; - + using (Process? process = Process.Start(startInfo)) { process?.WaitForExit(); @@ -1663,7 +1663,7 @@ private void RestartAsAdmin() Verb = "runas", Arguments = ConfigManager.StartSilent ? "/silent" : "" }; - + Process.Start(startInfo); System.Windows.Application.Current.Shutdown(); } diff --git a/src/MainWindow.xaml.cs b/src/MainWindow.xaml.cs index 3e828df..dfb74fc 100644 --- a/src/MainWindow.xaml.cs +++ b/src/MainWindow.xaml.cs @@ -325,7 +325,7 @@ private void OnWebViewProcessFailed(object? sender, CoreWebView2ProcessFailedEve if (_isClosing) return; if (_coreWebView != null && _processFailedHandler != null) { - try { _coreWebView.ProcessFailed -= _processFailedHandler; } catch { } + try { _coreWebView.ProcessFailed -= _processFailedHandler; } catch { /* ignore: event unsubscribe is best-effort */ } } _processFailedHandler = null; _coreWebView = null; @@ -351,7 +351,7 @@ private string BuildInputContextScript(string inputMode) { return string.Empty; } - + _lastReportedInputMode = inputMode; _lastReportedAlwaysTrail = alwaysTrailEnabled; string alwaysTrailLiteral = alwaysTrailEnabled ? "true" : "false"; diff --git a/src/OverlayManager.cs b/src/OverlayManager.cs index 5662819..31650a8 100644 --- a/src/OverlayManager.cs +++ b/src/OverlayManager.cs @@ -663,7 +663,7 @@ private void CloseOverlay(string deviceName) return; } - try { overlay.Close(); } catch (Exception ex) { Debug.WriteLine(ex.Message); } + try { overlay.Close(); } catch (Exception ex) { AppLogger.Warn($"Failed to close overlay for '{deviceName}': {ex.Message}"); } _overlays.Remove(deviceName); } diff --git a/src/TelemetryHelper.cs b/src/TelemetryHelper.cs index 8b0ab12..76c132b 100644 --- a/src/TelemetryHelper.cs +++ b/src/TelemetryHelper.cs @@ -68,7 +68,7 @@ public static async Task SendTelemetryAsync(string trigger) string clientId = EnsureClientId(); var payload = BuildPayload(clientId, trigger); string json = JsonSerializer.Serialize(payload); - + if (Encoding.UTF8.GetByteCount(json) > MaxPayloadBytes) { AppLogger.Warn("Telemetry payload exceeded size limit; skipped."); @@ -134,7 +134,7 @@ private static object BuildPayload(string clientId, string trigger) { var dm = new DEVMODE(); dm.dmSize = (short)Marshal.SizeOf(typeof(DEVMODE)); - + if (EnumDisplaySettings(screen.DeviceName, ENUM_CURRENT_SETTINGS, ref dm) && dm.dmDisplayFrequency > 1) { screensInfo.Add($"{dm.dmPelsWidth}x{dm.dmPelsHeight}@{dm.dmDisplayFrequency}Hz"); @@ -185,7 +185,7 @@ private static string GetCleanDotNetVersion() return desc.Replace(".NET Core", "Core").Replace(".NET", "").Trim(); } } - catch { } + catch { /* ignore: fallback to Environment.Version below */ } try { @@ -198,6 +198,7 @@ private static string GetCleanDotNetVersion() } catch { + /* ignore: cannot determine .NET version */ return "Unknown"; } } @@ -216,7 +217,7 @@ private static int GetRefreshRateViaWmiFallback() } } } - catch { } + catch { /* ignore: WMI unavailable, fallback to 60Hz */ } return 60; } @@ -233,7 +234,7 @@ private static string GetCpuName() using var searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT Name FROM Win32_Processor"); foreach (var obj in searcher.Get()) return obj["Name"]?.ToString() ?? "Unknown CPU"; } - catch { } + catch { /* ignore: WMI unavailable, fallback to 'Unknown CPU' */ } return "Unknown CPU"; } @@ -263,7 +264,7 @@ private static string GetGpuName() } return SanitizeGpuName(gpuList[0]); } - catch { } + catch { /* ignore: WMI unavailable, fallback to 'Unknown GPU' */ } return "Unknown GPU"; } @@ -290,7 +291,7 @@ private static string GetTotalMemoryGb() } } } - catch { } + catch { /* ignore: WMI unavailable, fallback to 'Unknown RAM' */ } return "Unknown RAM"; }