retep998 / winapi-rs

Rust bindings to Windows API
https://crates.io/crates/winapi
Apache License 2.0
1.85k stars 392 forks source link

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

Open Joe23232 opened 3 years ago

Joe23232 commented 3 years ago

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 commented 3 years ago

@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.