From fb662be70c7a0d318c65acf0c3ec0a144f5c02c7 Mon Sep 17 00:00:00 2001 From: lifegpc Date: Sat, 20 Jul 2024 19:48:25 +0800 Subject: [PATCH] Support hide console window when running games on Windows --- Cargo.lock | 1 + Cargo.toml | 3 +++ src/cfg.rs | 7 +++++++ src/main.rs | 18 ++++++++++++++++++ src/windows.rs | 19 +++++++++++++++++++ 5 files changed, 48 insertions(+) create mode 100644 src/windows.rs diff --git a/Cargo.lock b/Cargo.lock index ed676d4..dcddaff 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -28,6 +28,7 @@ dependencies = [ "derive_more", "getopts", "subprocess", + "winapi", "yaml-rust", ] diff --git a/Cargo.toml b/Cargo.toml index 089a6d4..5317ee1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,3 +8,6 @@ derive_more = "0.99.18" getopts = "0.2.21" subprocess = "0.2.9" yaml-rust = "0.4.5" + +[target.'cfg(windows)'.dependencies] +winapi = { version = "0.3", features = ["wincon", "winuser"] } diff --git a/src/cfg.rs b/src/cfg.rs index d808c88..d52c034 100644 --- a/src/cfg.rs +++ b/src/cfg.rs @@ -143,4 +143,11 @@ impl Config { pub fn rclone_flag(&self) -> Vec { self.get_str_vec("rclone_flag").unwrap_or(vec![]) } + + #[cfg(windows)] + pub fn hide_window_when_running_exe(&self) -> bool { + self.get_bool("hide_window_when_running_exe") + .map(|s| s.to_owned()) + .unwrap_or(true) + } } diff --git a/src/main.rs b/src/main.rs index fa606ea..80b23d8 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,5 +1,7 @@ mod cfg; mod utils; +#[cfg(windows)] +mod windows; use getopts::Options; use std::process::ExitCode; @@ -187,7 +189,23 @@ impl Main { println!("Run command line: {:?}", cml); Ok(()) } else { + #[cfg(windows)] + let need_hide = self._cfg.hide_window_when_running_exe(); + #[cfg(windows)] + let hide = if need_hide { + windows::hide_window() + } else { + false + }; + #[cfg(windows)] + if need_hide && !hide { + println!("Failed to hide console window."); + } let e = Self::call(cml)?; + #[cfg(windows)] + if hide { + windows::show_window(); + } let ok = match &e { ExitStatus::Exited(c) => *c == 0, _ => false, diff --git a/src/windows.rs b/src/windows.rs new file mode 100644 index 0000000..191f88c --- /dev/null +++ b/src/windows.rs @@ -0,0 +1,19 @@ +use winapi::um::wincon::GetConsoleWindow; +use winapi::um::winuser::{ShowWindow, SW_HIDE, SW_SHOW}; + +fn console_show_window(n_cmd_show: i32) -> bool { + let h_wnd = unsafe { GetConsoleWindow() }; + if h_wnd.is_null() { + println!("Failed to get console window."); + return false; + } + unsafe { ShowWindow(h_wnd, n_cmd_show) != 0 } +} + +pub fn show_window() -> bool { + console_show_window(SW_SHOW) +} + +pub fn hide_window() -> bool { + console_show_window(SW_HIDE) +}