优化了开机自启功能:

改为程序内部操作注册表,不需要额外启动命令行窗口,使其切换设置时更加快捷
可以检测当前是否启用了开机自启
尽可能的简化了代码
This commit is contained in:
Hgnim 2025-01-06 19:10:56 +08:00 committed by Space Time
parent 810ff86999
commit ea354cac72
2 changed files with 51 additions and 59 deletions

View File

@ -9,7 +9,7 @@
mc:Ignorable="d" mc:Ignorable="d"
d:DataContext="{d:DesignInstance preses:SettingsPres}" d:DataContext="{d:DesignInstance preses:SettingsPres}"
Style="{DynamicResource CommonWindow}" WindowStartupLocation="CenterScreen" ResizeMode="NoResize" SizeToContent="Height" Width="500" Style="{DynamicResource CommonWindow}" WindowStartupLocation="CenterScreen" ResizeMode="NoResize" SizeToContent="Height" Width="500"
KeyDown="SettingsWin_KeyDown"> KeyDown="SettingsWin_KeyDown" Loaded="Window_Loaded">
<Grid Margin="5"> <Grid Margin="5">
<Grid.RowDefinitions> <Grid.RowDefinitions>
<RowDefinition Height="*" /> <RowDefinition Height="*" />
@ -56,10 +56,8 @@
</Binding> </Binding>
</Button.Content> </Button.Content>
</Button> </Button>
<Button Grid.Row="2" Grid.Column="0" Margin="5" Content="启用/修复 程序开机自启动" ToolTip="{Binding Source={x:Static consts:SettingsConst.ColorsButtonToolTip}}" <Button x:Name="SelfStartingToggle" Grid.Row="2" Grid.Column="0" Margin="5" Content="/ / / /" ToolTip="{Binding Source={x:Static consts:SettingsConst.ColorsButtonToolTip}}"
Click="Enabled_SelfStarting_Click"/> Click="SelfStartingToggle_Click"/>
<Button Grid.Row="2" Grid.Column="1" Margin="5" Content="禁用 程序开机自启动" ToolTip="{Binding Source={x:Static consts:SettingsConst.ColorsButtonToolTip}}"
Click="Disabled_SelfStarting_Click" />
</Grid> </Grid>
</Window> </Window>

View File

@ -10,6 +10,7 @@ using Sheas_Cealer.Consts;
using Sheas_Cealer.Preses; using Sheas_Cealer.Preses;
using Sheas_Cealer.Props; using Sheas_Cealer.Props;
using Sheas_Cealer.Utils; using Sheas_Cealer.Utils;
using Microsoft.Win32;
namespace Sheas_Cealer.Wins; namespace Sheas_Cealer.Wins;
@ -65,21 +66,24 @@ public partial class SettingsWin : Window
Close(); Close();
} }
private void Enabled_SelfStarting_Click(object sender, RoutedEventArgs e) { readonly SelfStarting selfStarting = new();
SelfStarting ss = new(); private void SelfStartingToggle_Click(object sender, RoutedEventArgs e) {
if (ss.RunCommand(SelfStarting.Action.add)) //在此处为了方便演示,就直接使用了按钮名字进行判断,不建议这么做
MessageBox.Show("已启用开机自启"); if( SelfStartingToggle.Content as string == "启用>>禁用 程序开机自启动") {
selfStarting.Setting = false;
SelfStartingToggle.Content = "禁用>>启用 程序开机自启动";
}
else {
selfStarting.Setting = true;
SelfStartingToggle.Content = "启用>>禁用 程序开机自启动";
}
} }
private void Disabled_SelfStarting_Click(object sender, RoutedEventArgs e) {
SelfStarting ss = new(); private class SelfStarting {
if (ss.RunCommand(SelfStarting.Action.remove))
MessageBox.Show("已移除开机自启");
}
private class SelfStarting {
/// <summary> /// <summary>
/// 自启动注册表路径 /// 自启动注册表路径
/// </summary> /// </summary>
readonly string regPath = @"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run"; readonly string regPath = @"Software\Microsoft\Windows\CurrentVersion\Run";
/// <summary> /// <summary>
/// 应用名 /// 应用名
/// </summary> /// </summary>
@ -88,47 +92,37 @@ public partial class SettingsWin : Window
/// 当前exe文件所在目录 /// 当前exe文件所在目录
/// </summary> /// </summary>
internal string ThisExeFilePath => System.Windows.Forms.Application.ExecutablePath; internal string ThisExeFilePath => System.Windows.Forms.Application.ExecutablePath;
//自启动程序时会添加启动参数,可以在程序启动时加个判断,判断有-selfStarting参数时进行自动最小化程序等操作
string AddCommands => $"{RemoveCommands} & reg add {regPath} /f /v \"{appName}\" /t REG_SZ /d \"{ThisExeFilePath} -selfStarting\"";// & pause";
string RemoveCommands => $"reg delete {regPath} /f /v \"{appName}\"";
internal enum Action {
add,remove
}
/// <summary>
/// 运行命令
/// </summary>
/// <param name="action">操作方式</param>
/// <returns>返回布尔值代表执行是否成功</returns>
internal bool RunCommand(Action action) {
// 检查当前进程是否以管理员身份运行
//if (!new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator))
string commands = "";
switch (action) {
case Action.add:
commands = AddCommands; break;
case Action.remove:
commands = RemoveCommands; break;
}
Process process = new() { /// <summary>
StartInfo = new ProcessStartInfo { /// 设置开机自启
UseShellExecute = true, /// </summary>
Verb = "RunAs", // 请求管理员权限 internal bool Setting {
CreateNoWindow = true, get {
FileName = "cmd.exe", using RegistryKey? key = Registry.CurrentUser.OpenSubKey(regPath, false);
Arguments = $" /c \"{ commands }\"" return key?.GetValue(appName) != null;
} }
}; set {
bool isTrue = false; void DeleteReg() {
try { using RegistryKey? key = Registry.CurrentUser.OpenSubKey(regPath, true);
process.Start(); key?.DeleteValue(appName, false);
process.WaitForExit(); }
isTrue = true; switch (value) {
} case true: {
catch (Win32Exception) { System.Windows.Forms.MessageBox.Show("用户取消了授权", "", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); } DeleteReg();
catch { System.Windows.Forms.MessageBox.Show("发生未知错误!", "", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); } using RegistryKey? key = Registry.CurrentUser.OpenSubKey(regPath, true);
process.Close(); //自启动程序时会添加启动参数,可以在程序启动时加个判断,判断有-selfStarting参数时进行自动最小化程序等操作
return isTrue; key?.SetValue(appName, $"{ThisExeFilePath} -selfStarting", RegistryValueKind.String);
} break;
} }
case false:
DeleteReg();
break;
}
}
}
}
private void Window_Loaded(object sender, RoutedEventArgs e) =>
//检查当前选项状态
SelfStartingToggle.Content = selfStarting.Setting ? "启用>>禁用 程序开机自启动" : "禁用>>启用 程序开机自启动";
} }