Suppressing the console (window) for a GUI app in windows, while keeping output working?

So far been using #![windows_subsystem = "windows"] to get rid of it, but I want to add CLI support to my application and I haven't found a way to allow that. Adding the snippet above hides the console but seems to have the side effect of disabling any text being outputted.

Any ideas of what to try?

Just to clarify, you want to show output when it's run from the command line but not show output if someone runs the program from explorer?

I want to show output when ran from the command line, but hide the console window that pops up along with the GUI when run with GUI (not necessarily hide the output, just the cmd window)

Hm, that's not easy to do on Windows. Instead of using windows_subsystem, you'll need to detect at run time how the program was invoked.

fn main(){
    println!("Hello world!");
    if !is_console() {
        free_console();
    }
    // run gui here.
}

fn free_console() -> bool {
    unsafe { FreeConsole() } == 0
}
fn is_console() -> bool {
    unsafe {
        let mut buffer = [0u32; 1];
        let count = GetConsoleProcessList(buffer.as_mut_ptr(), 1);
        count != 1
    }
}
#[link(name="Kernel32")]
extern "system" {
    fn GetConsoleProcessList(processList: *mut u32, count: u32) -> u32;
    fn FreeConsole() -> i32;
}

The downside is there may be a brief flash of a console window.

The other option would be to split the program in two. One with console output and one without. They could both, for example, load the same dll that does the real work. But admittedly that's more complex (both for you and users).

1 Like

Thats a shame, thanks for the code though, will try it later and see how that goes.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.