Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 10 additions & 10 deletions src/App.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 };
Expand Down Expand Up @@ -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 */ }
Comment thread
ABA2396 marked this conversation as resolved.
try { Overlay?.Dispose(); } catch { /* ignore: best-effort cleanup during shutdown */ }
Comment thread
ABA2396 marked this conversation as resolved.
});

if (_mutex != null)
{
try { _mutex.ReleaseMutex(); } catch { }
try { _mutex.ReleaseMutex(); } catch { /* ignore: mutex disposal during shutdown */ }
Comment thread
ABA2396 marked this conversation as resolved.
_mutex.Dispose();
_mutex = null;
}
Expand Down
27 changes: 21 additions & 6 deletions src/ConfigManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,11 @@ public static void Load()
{
_profiles = System.Text.Json.JsonSerializer.Deserialize<List<FilterProfile>>(FilterProfiles) ?? new List<FilterProfile>();
}
catch { _profiles = new List<FilterProfile>(); }
catch (Exception ex)
{
AppLogger.Warn($"Failed to deserialize FilterProfiles; fallback to empty list: {ex.Message}");
Comment thread
ABA2396 marked this conversation as resolved.
_profiles = new List<FilterProfile>();
}
}

// 向后兼容处理
Expand Down Expand Up @@ -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}");
Comment thread
ABA2396 marked this conversation as resolved.
}
}

public static PanelScrollbarVisibility ParseScrollbarVisibility(string? raw)
Expand Down Expand Up @@ -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}");
Comment thread
ABA2396 marked this conversation as resolved.
}
}

public static IReadOnlySet<string> GetProcessFilterEntries()
Expand All @@ -353,8 +363,9 @@ public static HashSet<string> GetEnabledScreenIds()
.Select(s => s.Trim())
.ToHashSet(StringComparer.OrdinalIgnoreCase);
}
catch
catch (Exception ex)
{
AppLogger.Warn($"Failed to parse EnabledScreenIds; fallback to empty set: {ex.Message}");
Comment thread
ABA2396 marked this conversation as resolved.
return new HashSet<string>(StringComparer.OrdinalIgnoreCase);
}
}
Expand Down Expand Up @@ -382,8 +393,9 @@ public static List<ScreenSelectionState> GetScreenSelections()
{
return System.Text.Json.JsonSerializer.Deserialize<List<ScreenSelectionState>>(ScreenSelections) ?? new List<ScreenSelectionState>();
}
catch
catch (Exception ex)
{
AppLogger.Warn($"Failed to parse ScreenSelections; fallback to empty list: {ex.Message}");
Comment thread
ABA2396 marked this conversation as resolved.
return new List<ScreenSelectionState>();
}
}
Expand Down Expand Up @@ -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}");
Comment thread
ABA2396 marked this conversation as resolved.
}
}
}
}
26 changes: 13 additions & 13 deletions src/ControlPanelWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -511,7 +511,7 @@
}
}
}
catch (Exception ex) { Debug.WriteLine(ex.Message); }
catch (Exception ex) { AppLogger.Warn($"Failed to enumerate running processes: {ex.Message}"); }
Comment thread
ABA2396 marked this conversation as resolved.
}

private void SearchRunningProcess_TextChanged(object sender, TextChangedEventArgs e)
Expand Down Expand Up @@ -561,7 +561,7 @@
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;
Expand Down Expand Up @@ -816,7 +816,7 @@
CheckShowEffectOnDesktop.IsEnabled = environmentFilterEnabled;
ComboProfiles.IsEnabled = environmentFilterEnabled;
ComboProcessFilterMode.IsEnabled = environmentFilterEnabled;

if (ListConfiguredProcesses != null)
{
ListConfiguredProcesses.IsEnabled = processFilterEnabled;
Expand Down Expand Up @@ -966,7 +966,7 @@
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)
{
Expand Down Expand Up @@ -1115,7 +1115,7 @@
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;
Expand Down Expand Up @@ -1389,7 +1389,7 @@

bool telemetryEnabled = CheckTelemetry.IsChecked ?? false;
bool telemetryWasEnabled = ConfigManager.EnableTelemetry;

// 保存配置组
string activeId = (ComboProfiles.SelectedItem as FilterProfile)?.Id ?? "";
ConfigManager.SaveProfiles(Profiles.ToList(), activeId);
Expand Down Expand Up @@ -1498,7 +1498,7 @@
Localization.Get("Msg_AdminRestart_Title"),
MessageBoxButton.YesNo,
MessageBoxImage.Question);

if (res == MessageBoxResult.Yes)
{
RestartAsAdmin();
Expand Down Expand Up @@ -1582,18 +1582,18 @@
{
bool autoStart = CheckAutoStart.IsChecked == true;
bool runAsAdmin = CheckRunAsAdmin.IsChecked == true;

string? exePath = AutoStartManager.ResolveExecutablePath(
Environment.ProcessPath,
Process.GetCurrentProcess().MainModule?.FileName,
Assembly.GetExecutingAssembly().Location,

Check warning on line 1589 in src/ControlPanelWindow.xaml.cs

View workflow job for this annotation

GitHub Actions / build

'System.Reflection.Assembly.Location' always returns an empty string for assemblies embedded in a single-file app. If the path to the app directory is needed, consider calling 'System.AppContext.BaseDirectory'.
AppDomain.CurrentDomain.BaseDirectory);

if (string.IsNullOrEmpty(exePath)) return;

string regKeyPath = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run";
AutoStartPlan plan = AutoStartManager.CreatePlan(autoStart, runAsAdmin);

try
{
using (RegistryKey? key = Registry.CurrentUser.CreateSubKey(regKeyPath, true))
Expand All @@ -1620,8 +1620,8 @@
{
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
Expand All @@ -1633,7 +1633,7 @@
WindowStyle = ProcessWindowStyle.Hidden,
Verb = new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator) ? "" : "runas"
};

using (Process? process = Process.Start(startInfo))
{
process?.WaitForExit();
Expand Down Expand Up @@ -1663,7 +1663,7 @@
Verb = "runas",
Arguments = ConfigManager.StartSilent ? "/silent" : ""
};

Process.Start(startInfo);
System.Windows.Application.Current.Shutdown();
}
Expand Down
4 changes: 2 additions & 2 deletions src/MainWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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 */ }
Comment thread
ABA2396 marked this conversation as resolved.
}
_processFailedHandler = null;
_coreWebView = null;
Expand All @@ -351,7 +351,7 @@ private string BuildInputContextScript(string inputMode)
{
return string.Empty;
}

_lastReportedInputMode = inputMode;
_lastReportedAlwaysTrail = alwaysTrailEnabled;
string alwaysTrailLiteral = alwaysTrailEnabled ? "true" : "false";
Expand Down
2 changes: 1 addition & 1 deletion src/OverlayManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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}"); }
Comment thread
ABA2396 marked this conversation as resolved.
_overlays.Remove(deviceName);
}

Expand Down
15 changes: 8 additions & 7 deletions src/TelemetryHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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.");
Expand Down Expand Up @@ -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");
Expand Down Expand Up @@ -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
{
Expand All @@ -198,6 +198,7 @@ private static string GetCleanDotNetVersion()
}
catch
{
/* ignore: cannot determine .NET version */
return "Unknown";
}
}
Expand All @@ -216,7 +217,7 @@ private static int GetRefreshRateViaWmiFallback()
}
}
}
catch { }
catch { /* ignore: WMI unavailable, fallback to 60Hz */ }
return 60;
}

Expand All @@ -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";
}

Expand Down Expand Up @@ -263,7 +264,7 @@ private static string GetGpuName()
}
return SanitizeGpuName(gpuList[0]);
}
catch { }
catch { /* ignore: WMI unavailable, fallback to 'Unknown GPU' */ }
return "Unknown GPU";
}

Expand All @@ -290,7 +291,7 @@ private static string GetTotalMemoryGb()
}
}
}
catch { }
catch { /* ignore: WMI unavailable, fallback to 'Unknown RAM' */ }
return "Unknown RAM";
}

Expand Down
Loading