From 79aad6b5c2e7a2d1f61b3368b6ee1d58e77a6669 Mon Sep 17 00:00:00 2001 From: GyDi Date: Tue, 11 Jan 2022 02:21:35 +0800 Subject: [PATCH] feat: window self startup --- src-tauri/src/utils/mod.rs | 1 + src-tauri/src/utils/startup.rs | 62 ++++++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+) create mode 100644 src-tauri/src/utils/startup.rs diff --git a/src-tauri/src/utils/mod.rs b/src-tauri/src/utils/mod.rs index a5fe22b..2ba9a57 100644 --- a/src-tauri/src/utils/mod.rs +++ b/src-tauri/src/utils/mod.rs @@ -4,4 +4,5 @@ pub mod fetch; pub mod init; pub mod resolve; pub mod server; +pub mod startup; pub mod sysopt; diff --git a/src-tauri/src/utils/startup.rs b/src-tauri/src/utils/startup.rs new file mode 100644 index 0000000..f2d8266 --- /dev/null +++ b/src-tauri/src/utils/startup.rs @@ -0,0 +1,62 @@ +use std::io; +use std::path::PathBuf; + +static APP_KEY: &str = "ClashVerge"; + +#[cfg(target_os = "windows")] +/// get the startup value +/// whether as same as the exe_path +pub fn get_startup(exe_path: &PathBuf) -> io::Result { + use winreg::enums::*; + use winreg::RegKey; + + let hkcu = RegKey::predef(HKEY_CURRENT_USER); + let cur_var = hkcu.open_subkey_with_flags( + "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", + KEY_READ, + )?; + + match cur_var.get_value::(APP_KEY) { + Ok(path) => { + let exe_path = exe_path.clone(); + let exe_path = exe_path.as_os_str().to_str().unwrap(); + Ok(path == exe_path) + } + Err(_) => Ok(false), + } +} + +#[cfg(target_os = "windows")] +/// set the startup on windows +/// delete the reg key if disabled +pub fn set_startup(enable: bool, exe_path: &PathBuf) -> io::Result<()> { + use winreg::enums::*; + use winreg::RegKey; + + let hkcu = RegKey::predef(HKEY_CURRENT_USER); + let cur_var = hkcu.open_subkey_with_flags( + "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", + KEY_SET_VALUE, + )?; + + match enable { + true => { + let exe_path = exe_path.clone(); + let exe_path = exe_path.as_os_str().to_str().unwrap(); + cur_var.set_value::<&str, _>(APP_KEY, &exe_path) + } + false => cur_var.delete_value(APP_KEY), + } +} + +#[cfg(target_os = "windows")] +#[test] +fn test() { + let path = PathBuf::from(r"D:\Software\Clash Verge\clash-verge.exe"); + + assert!(set_startup(true, &path).is_ok()); + assert_eq!(get_startup(&path).unwrap(), true); + + assert!(set_startup(false, &path).is_ok()); + assert_eq!(get_startup(&path).unwrap(), false); +}