winapi-rs icon indicating copy to clipboard operation
winapi-rs copied to clipboard

How do I disable the terminal from opening up when executing my Rust code?

Open Joe23232 opened this issue 4 years ago • 1 comments

Hey guys, so on Windows normally when you compile your code it generates an executable, so when I click on it it always opens up a temrinal window. I want to disable it showing a terminal window. I tried adding this to the beginning of my code:

#![windows_subsystem = "windows"]

I am using this but like it still shows the terminal window and in some cases it would open up multiple ones but this time with no output. I am not too sure why this is happening and if there is a way to stop the terminal from completely showing up at all?

From this post I have tried to even use this code:

fn hide_console_window() {
    use std::ptr;
    use winapi::um::wincon::GetConsoleWindow;
    use winapi::um::winuser::{ShowWindow, SW_HIDE};

    let window = unsafe {GetConsoleWindow()};
    // https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-showwindow
    if window != ptr::null_mut() {
        unsafe {
            ShowWindow(window, SW_HIDE);
        }
    }
}

Which appeared to have not done much. Any ideas/suggestions?

Here is my code:

So this is main.rs

// Disable terminal
#![windows_subsystem = "windows"]

use std::process::Command;

fn main()
{
    hide_console_window();
    
    let output = 
    Command::new("cmd.exe")
    .arg("/c")
    .arg("ping")
    .arg("www.google.com")
    .output()
    .unwrap();

    let output = output.status.to_string();

    //println!("{}", output);
}

fn hide_console_window()
{
    use std::ptr;
    use winapi::um::wincon::GetConsoleWindow;
    use winapi::um::winuser::{ShowWindow, SW_HIDE};

    let window = unsafe {GetConsoleWindow()};
    // https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-showwindow
    if window != ptr::null_mut()
    {
        unsafe
        {
            ShowWindow(window, SW_HIDE);
        }
    }
}

And this is my cargo dependences:

cargo.toml

[dependencies]
winapi = {version = "0.3", features = ["wincon", "winuser"]}

Joe23232 avatar Aug 01 '21 06:08 Joe23232

@lj7711622 I found the solution though:

pub fn hide_console_window()
{
    use winapi::um::{wincon::GetConsoleWindow, winuser::{SW_HIDE, ShowWindow}};
    
    unsafe
    {
        let window = GetConsoleWindow();
        if !window.is_null()
        {
            ShowWindow(window, SW_HIDE);
        }
    }
}

This is what you wanna do.

Joe23232 avatar Aug 13 '21 10:08 Joe23232