desktop: Change Windows Subsystem to not launch unnecessary console

Basically just copied from what alacritty is doing:
530de00049/alacritty/src/main.rs

There are two functional changes:
- When launching normally, you no longer see a console window quickly flashing
- When launching via. console, the program is detached (but still logs to the console)
This commit is contained in:
Mads Marquart 2021-01-24 23:58:17 +01:00 committed by Mike Welsh
parent 306d2ead7f
commit ad137a2377
1 changed files with 21 additions and 20 deletions

View File

@ -1,3 +1,10 @@
// By default, Windows creates an additional console window for our program.
//
//
// This is silently ignored on non-windows systems.
// See https://docs.microsoft.com/en-us/cpp/build/reference/subsystem?view=msvc-160 for details.
#![windows_subsystem = "windows"]
mod audio; mod audio;
mod custom_event; mod custom_event;
mod executor; mod executor;
@ -102,7 +109,14 @@ fn trace_path(_opt: &Opt) -> Option<&Path> {
} }
fn main() { fn main() {
win32_hide_console(); // When linked with the windows subsystem windows won't automatically attach
// to the console of the parent process, so we do it explicitly. This fails
// silently if the parent has no console.
#[cfg(windows)]
unsafe {
use winapi::um::wincon::{AttachConsole, ATTACH_PARENT_PROCESS};
AttachConsole(ATTACH_PARENT_PROCESS);
}
env_logger::init(); env_logger::init();
@ -118,6 +132,12 @@ fn main() {
eprintln!("Fatal error:\n{}", e); eprintln!("Fatal error:\n{}", e);
std::process::exit(-1); std::process::exit(-1);
} }
// Without explicitly detaching the console cmd won't redraw it's prompt.
#[cfg(windows)]
unsafe {
winapi::um::wincon::FreeConsole();
}
} }
fn load_movie_from_path(movie_url: Url, opt: &Opt) -> Result<SwfMovie, Box<dyn std::error::Error>> { fn load_movie_from_path(movie_url: Url, opt: &Opt) -> Result<SwfMovie, Box<dyn std::error::Error>> {
@ -492,22 +512,3 @@ fn run_timedemo(opt: Opt) -> Result<(), Box<dyn std::error::Error>> {
Ok(()) Ok(())
} }
/// Hides the Win32 console if we were not launched from the command line.
fn win32_hide_console() {
#[cfg(windows)]
unsafe {
use winapi::um::{wincon::*, winuser::*};
// If we have a console, and we are the exclusive process using that console,
// then we were not launched from the command-line; hide the console to act like a GUI app.
let hwnd = GetConsoleWindow();
if !hwnd.is_null() {
let mut pids = [0; 2];
let num_pids = GetConsoleProcessList(pids.as_mut_ptr(), 2);
let is_exclusive = num_pids <= 1;
if is_exclusive {
ShowWindow(hwnd, SW_HIDE);
}
}
}
}