'How do I have a hidden console when using windows_subsystem?

My goal is to have it so when the executable is just double clicked no console spawns but also have it able to print to the console when the user launches it from the command line.

I have the following Windows-specific code set to not spawn a console:

#![windows_subsystem = "windows"]
fn main() {
    println!("Hello world");
}

Unfortunately, it never hooks stdout/stderr to anything since its set to not create a console on startup. Is there any way to achieve my goal despite this?



Solution 1:[1]

This is not really specific to Rust, but instead is the way Windows works: you either write for the "console" subsystem and your program opens a console if it is started without one, or you write for the "windows" subsystem and your program detaches itself from the console if it is started from the command line.

The PATHEXT environment variable — which CLI shells use for the file extensions to add when searching PATH for a command — normally includes ".COM" before ".EXE", in which case one can create a console version of the application with a ".com" file extension (e.g. "app.com"). This can be a standalone version or just a launcher that spawns the main executable (e.g. "app.exe", a GUI app). A launcher can pass a command-line option that allows the main application to attach back to the console via AttachConsole.

Without a launcher, it's a bad idea to attach back to the console since the parent application (e.g. a CLI shell or a full TUI app) normally will not wait for a GUI application to exit, in which case the result is chaotic interleaved I/O with two applications competing for access.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1