🎨 Updated
This commit is contained in:
@@ -43,11 +43,5 @@ func (s *StartupService) SetEnabled(enabled bool) error {
|
||||
if err := s.impl.SetEnabled(enabled); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 更新配置文件
|
||||
if s.configService != nil {
|
||||
s.configService.Set("general.startAtLogin", enabled)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
@@ -5,6 +5,7 @@ package services
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
@@ -18,7 +19,7 @@ type WindowsStartupImpl struct {
|
||||
registryKey string
|
||||
execPath string
|
||||
workingDir string
|
||||
batchFile string
|
||||
taskName string // 任务计划程序任务名
|
||||
}
|
||||
|
||||
// newStartupImplementation 创建平台特定的开机启动实现
|
||||
@@ -48,12 +49,88 @@ func (w *WindowsStartupImpl) Initialize() error {
|
||||
// 获取工作目录(可执行文件所在目录)
|
||||
w.workingDir = filepath.Dir(w.execPath)
|
||||
|
||||
// 使用文件名作为注册表键名
|
||||
w.registryKey = strings.TrimSuffix(filepath.Base(w.execPath), filepath.Ext(w.execPath))
|
||||
// 使用文件名作为注册表键名和任务名
|
||||
baseName := strings.TrimSuffix(filepath.Base(w.execPath), filepath.Ext(w.execPath))
|
||||
w.registryKey = baseName
|
||||
w.taskName = baseName + "_Startup"
|
||||
|
||||
// 批处理文件路径(放在临时目录)
|
||||
tempDir := os.TempDir()
|
||||
w.batchFile = filepath.Join(tempDir, w.registryKey+"_startup.bat")
|
||||
return nil
|
||||
}
|
||||
|
||||
// createTaskSchedulerEntry 创建任务计划程序条目
|
||||
func (w *WindowsStartupImpl) createTaskSchedulerEntry() error {
|
||||
// 创建任务计划程序条目的XML内容
|
||||
taskXML := fmt.Sprintf(`<?xml version="1.0" encoding="UTF-16"?>
|
||||
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
|
||||
<RegistrationInfo>
|
||||
<Description>%s startup task</Description>
|
||||
</RegistrationInfo>
|
||||
<Triggers>
|
||||
<LogonTrigger>
|
||||
<Enabled>true</Enabled>
|
||||
</LogonTrigger>
|
||||
</Triggers>
|
||||
<Principals>
|
||||
<Principal id="Author">
|
||||
<LogonType>InteractiveToken</LogonType>
|
||||
<RunLevel>HighestAvailable</RunLevel>
|
||||
</Principal>
|
||||
</Principals>
|
||||
<Settings>
|
||||
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
|
||||
<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
|
||||
<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
|
||||
<AllowHardTerminate>true</AllowHardTerminate>
|
||||
<StartWhenAvailable>false</StartWhenAvailable>
|
||||
<RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
|
||||
<IdleSettings>
|
||||
<StopOnIdleEnd>true</StopOnIdleEnd>
|
||||
<RestartOnIdle>false</RestartOnIdle>
|
||||
</IdleSettings>
|
||||
<AllowStartOnDemand>true</AllowStartOnDemand>
|
||||
<Enabled>true</Enabled>
|
||||
<Hidden>false</Hidden>
|
||||
<RunOnlyIfIdle>false</RunOnlyIfIdle>
|
||||
<WakeToRun>false</WakeToRun>
|
||||
<ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
|
||||
<Priority>7</Priority>
|
||||
</Settings>
|
||||
<Actions Context="Author">
|
||||
<Exec>
|
||||
<Command>%s</Command>
|
||||
<WorkingDirectory>%s</WorkingDirectory>
|
||||
</Exec>
|
||||
</Actions>
|
||||
</Task>`, w.taskName, w.execPath, w.workingDir)
|
||||
|
||||
// 创建临时XML文件
|
||||
tempFile := filepath.Join(os.TempDir(), w.taskName+".xml")
|
||||
if err := os.WriteFile(tempFile, []byte(taskXML), 0644); err != nil {
|
||||
return fmt.Errorf("failed to create task XML file: %w", err)
|
||||
}
|
||||
defer os.Remove(tempFile) // 清理临时文件
|
||||
|
||||
// 使用schtasks命令创建任务
|
||||
cmd := exec.Command("schtasks", "/create", "/tn", w.taskName, "/xml", tempFile, "/f")
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create scheduled task: %w, output: %s", err, string(output))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// deleteTaskSchedulerEntry 删除任务计划程序条目
|
||||
func (w *WindowsStartupImpl) deleteTaskSchedulerEntry() error {
|
||||
cmd := exec.Command("schtasks", "/delete", "/tn", w.taskName, "/f")
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
// 如果任务不存在
|
||||
if strings.Contains(string(output), "cannot find") || strings.Contains(string(output), "does not exist") {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("failed to delete scheduled task: %w, output: %s", err, string(output))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -71,43 +148,44 @@ func (w *WindowsStartupImpl) openRegistryKey() (registry.Key, error) {
|
||||
return key, nil
|
||||
}
|
||||
|
||||
// createBatchFile 创建批处理文件
|
||||
func (w *WindowsStartupImpl) createBatchFile() error {
|
||||
// 批处理文件内容
|
||||
batchContent := fmt.Sprintf(`@echo off
|
||||
cd /d "%s"
|
||||
start "" "%s"
|
||||
`, w.workingDir, w.execPath)
|
||||
|
||||
// 写入批处理文件
|
||||
if err := os.WriteFile(w.batchFile, []byte(batchContent), 0644); err != nil {
|
||||
return fmt.Errorf("failed to create batch file: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// deleteBatchFile 删除批处理文件
|
||||
func (w *WindowsStartupImpl) deleteBatchFile() {
|
||||
if _, err := os.Stat(w.batchFile); err == nil {
|
||||
os.Remove(w.batchFile)
|
||||
}
|
||||
}
|
||||
|
||||
// buildStartupCommand 构建启动命令
|
||||
func (w *WindowsStartupImpl) buildStartupCommand() (string, error) {
|
||||
// 尝试直接使用可执行文件路径
|
||||
execPath := w.execPath
|
||||
|
||||
if strings.Contains(execPath, " ") {
|
||||
execPath = `"` + execPath + `"`
|
||||
}
|
||||
|
||||
// 首先尝试直接路径,如果有问题再使用批处理文件
|
||||
return execPath, nil
|
||||
}
|
||||
|
||||
// SetEnabled 设置开机启动状态
|
||||
func (w *WindowsStartupImpl) SetEnabled(enabled bool) error {
|
||||
if enabled {
|
||||
// 优先使用任务计划程序方式,可以绕过UAC限制
|
||||
if err := w.createTaskSchedulerEntry(); err != nil {
|
||||
// 如果任务计划程序失败,回退到注册表方式
|
||||
return w.setRegistryStartup(true)
|
||||
}
|
||||
return nil
|
||||
} else {
|
||||
|
||||
// 删除任务计划程序条目
|
||||
if err := w.deleteTaskSchedulerEntry(); err != nil {
|
||||
w.logger.Error("Failed to delete scheduled task", "error", err)
|
||||
}
|
||||
|
||||
// 删除注册表条目
|
||||
if err := w.setRegistryStartup(false); err != nil {
|
||||
w.logger.Error("Failed to remove registry startup entry", "error", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// setRegistryStartup 设置注册表启动项(备用方法)
|
||||
func (w *WindowsStartupImpl) setRegistryStartup(enabled bool) error {
|
||||
key, err := w.openRegistryKey()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to access registry: %w", err)
|
||||
@@ -120,8 +198,6 @@ func (w *WindowsStartupImpl) SetEnabled(enabled bool) error {
|
||||
return fmt.Errorf("failed to build startup command: %w", err)
|
||||
}
|
||||
|
||||
w.logger.Info("Setting Windows startup", "command", startupCmd)
|
||||
|
||||
if err := key.SetStringValue(w.registryKey, startupCmd); err != nil {
|
||||
return fmt.Errorf("failed to set startup entry: %w", err)
|
||||
}
|
||||
@@ -130,21 +206,15 @@ func (w *WindowsStartupImpl) SetEnabled(enabled bool) error {
|
||||
if value, _, err := key.GetStringValue(w.registryKey); err != nil {
|
||||
return fmt.Errorf("startup entry verification failed: %w", err)
|
||||
} else if value != startupCmd {
|
||||
w.logger.Error("Startup command verification mismatch", "expected", startupCmd, "actual", value)
|
||||
return fmt.Errorf("startup command verification failed: expected %s, got %s", startupCmd, value)
|
||||
}
|
||||
|
||||
w.logger.Info("Windows startup enabled successfully")
|
||||
} else {
|
||||
// 删除批处理文件(如果存在)
|
||||
w.deleteBatchFile()
|
||||
|
||||
if err := key.DeleteValue(w.registryKey); err != nil {
|
||||
// 如果键不存在,这不是错误
|
||||
if err != registry.ErrNotExist {
|
||||
return fmt.Errorf("failed to remove startup entry: %w", err)
|
||||
}
|
||||
}
|
||||
w.logger.Info("Windows startup disabled successfully")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
Reference in New Issue
Block a user