如何制作一个不显示控制台的程序window?

How to make a program that does not display the console window?

我正在尝试开发一个使用 sdl2 库的程序。到目前为止它工作得很好,但是当我 运行 程序时,我得到两个 windows - sdl2 window 和控制台 window.

如何隐藏或不创建控制台window?也许有某种 WinMain?

Rust 1.18 引入了 Windows 子系统属性。使用以下命令关闭控制台:

#![windows_subsystem = "windows"]

当 Rust 二进制文件与 GCC 工具链链接时,要在不生成命令行的情况下启动程序 window 我们需要 pass the -mwindows option to the linker.

货物has a cargo rustc mode which can be used to pass extra flags to rustc. Before that was introduced, there was no known way to pass an option to the compiler with Cargo.

当我们无法影响编译或链接到所需的效果时,一种解决方法是在创建后隐藏 window:

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);
        }
    }
}

我们需要 Cargo.toml 中的以下内容来编译示例:

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

当我们运行来自现有控制台的程序或IDE:

fn hide_console_window() {
    unsafe { winapi::um::wincon::FreeConsole() };
}

如果我们从批处理文件启动应用程序,则第二种方法不起作用,因为批处理仍然拥有控制台并防止其消失。

一段时间后我找到了一个完美的答案! Cargo 现在有非常有用的子命令 - rustc.

完整的构建命令是这样的:

cargo rustc -- -Clink-args="-Wl,--subsystem,windows"

现在我们可以使用常规 cargo build 构建调试版本,当我们需要进行最终构建时,我们可以使用此命令:

cargo rustc --release -- -Clink-args="-Wl,--subsystem,windows"

添加到 Roman Quick 的回答中,如果您使用的是 MSVC 工具链,您将希望改为传递 MSVC 链接器参数。

cargo rustc --release -- -Clink-args="/SUBSYSTEM:WINDOWS /ENTRY:mainCRTStartup"

很快,https://github.com/rust-lang/rust/pull/37501 will land, which is an implementation of RFC 1665,正确答案将是

#![windows_subsystem = "windows"]

在你的箱根。