Files
JoyD/Windows/CS/Framework4.0/BootLoader/src/main.rs
2026-04-07 11:10:40 +08:00

88 lines
2.6 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

use std::fs;
use std::process::Command;
use std::thread::sleep;
use std::time::Duration;
use windows::Win32::System::Console;
use windows::Win32::Foundation::HWND;
fn hide_console() {
unsafe {
let console = Console::GetConsoleWindow();
if console != HWND::default() {
let _ = Console::FreeConsole();
}
}
}
fn main() {
// 隐藏控制台窗口
hide_console();
// 检查是否已有 BootLoader 进程在运行
if is_process_running("BootLoader.exe") {
return;
}
// 获取 BootLoader 启动目录所在盘的 AppData 目录
let appdata_dir = get_appdata_dir();
// 构建 Updater 相关文件路径
let updater_exe = appdata_dir.join("Updater.exe");
let updater_new_exe = appdata_dir.join("Updater.new.exe");
// 检查 Updater.new.exe 是否存在
if !updater_new_exe.exists() {
return;
}
// 等待 Updater 进程退出
wait_for_process_exit("Updater.exe");
// 直接覆盖 Updater.exefs::rename 在 Windows 上会自动替换已存在的文件)
fs::rename(&updater_new_exe, &updater_exe).expect("Failed to rename Updater.new.exe to Updater.exe");
// 启动 Updater.exe
Command::new(updater_exe)
.spawn()
.expect("Failed to start Updater.exe");
}
fn is_process_running(process_name: &str) -> bool {
let output = Command::new("tasklist")
.args(["/FI", &format!("IMAGENAME eq {}", process_name)])
.output()
.expect("Failed to execute tasklist");
let output_str = String::from_utf8_lossy(&output.stdout);
output_str.contains(process_name)
}
fn get_appdata_dir() -> std::path::PathBuf {
let exe_path = std::env::current_exe().expect("Failed to get executable path");
let drive = if let Some(parent) = exe_path.parent() {
let drive = parent.as_os_str().to_str().unwrap_or("C:/").split('\\').next().unwrap_or("C:");
std::path::Path::new(&format!("{}/", drive)).to_path_buf()
} else {
std::path::Path::new("C:/").to_path_buf()
};
drive.join("AppData").join("Updater")
}
fn wait_for_process_exit(process_name: &str) {
loop {
// 使用 tasklist 命令检查进程是否存在
let output = Command::new("tasklist")
.args(["/FI", &format!("IMAGENAME eq {}", process_name)])
.output()
.expect("Failed to execute tasklist");
let output_str = String::from_utf8_lossy(&output.stdout);
if !output_str.contains(process_name) {
break;
}
// 等待 100 毫秒后再次检查
sleep(Duration::from_millis(100));
}
}