add try catch load settings

This commit is contained in:
thuannd88
2024-09-09 10:58:44 +07:00
parent 9bce66dfad
commit 7f0a9bf1c8
+43 -20
View File
@@ -31,24 +31,39 @@ namespace SafeBagDE70.Admin
public AdminSettingsUC() public AdminSettingsUC()
{ {
InitializeComponent(); InitializeComponent();
LoadStartupSetting(); try
timePicker.SelectedTime = Properties.Settings.Default.RestartTime; {
SetupAutoRestart(); LoadStartupSetting();
timePicker.SelectedTime = Properties.Settings.Default.RestartTime;
SetupAutoRestart();
}
catch (Exception ex) {
Log.Fatal(ex, "AdminSettingsUC");
}
} }
private void LoadStartupSetting() private void LoadStartupSetting()
{ {
// Open the registry key for the current user's startup applications try
RegistryKey key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", false);
appName = Assembly.GetEntryAssembly()?.GetName().Name;
if (key != null)
{ {
// Check if the app is already set to start with Windows // Open the registry key for the current user's startup applications
string value = key.GetValue(appName) as string; RegistryKey key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", false);
appName = Assembly.GetEntryAssembly()?.GetName().Name;
if (key != null)
{
// Check if the app is already set to start with Windows
string value = key.GetValue(appName) as string;
// If the app is listed in the startup items, set the checkbox to checked // If the app is listed in the startup items, set the checkbox to checked
cbStartWithWindows.IsChecked = value != null; cbStartWithWindows.IsChecked = value != null;
}
} }
catch (Exception ex)
{
Log.Fatal(ex, "LoadStartupSetting");
}
} }
private void cbStartWithWindows_Checked(object sender, RoutedEventArgs e) private void cbStartWithWindows_Checked(object sender, RoutedEventArgs e)
{ {
@@ -64,17 +79,25 @@ namespace SafeBagDE70.Admin
private void AddApplicationToStartup() private void AddApplicationToStartup()
{ {
// Get the path to the executable try
string exePath = Process.GetCurrentProcess().MainModule.FileName;
// Open the registry key for the current user's startup applications
RegistryKey key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
if (key != null)
{ {
// Add the application to the startup list // Get the path to the executable
key.SetValue(appName, exePath); string exePath = Process.GetCurrentProcess().MainModule.FileName;
// Open the registry key for the current user's startup applications
RegistryKey key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
if (key != null)
{
// Add the application to the startup list
key.SetValue(appName, exePath);
}
} }
catch (Exception ex)
{
Log.Fatal(ex, "AddApplicationToStartup");
}
} }
private void RemoveApplicationFromStartup() private void RemoveApplicationFromStartup()