是否可以使用标准库生成进程而不在 Windows 中显示控制台窗口?



这就是我现在拥有的:

Command::new("/path/to/application")
.args("-param")
.spawn()

看起来 Rust 使用CreateProcessW来运行 Windows 进程,这允许创建标志。也许有一个标志可以满足我的需要?

您可以使用std::os::windows::process::CommandExt::creation_flags.请参阅进程创建标志的文档页面,或理想情况下使用 winapi 中的常量。

您写道这是一个 GUI 应用程序,所以我假设您不需要这个应用程序的控制台输出。DETACHED_PROCESS不会创建 conhost.exe,但如果要处理输出,则应使用CREATE_NO_WINDOW

我还建议使用start作为命令,否则您将不得不使用cmd.exe,这可能会将启动延迟几毫秒。

use std::process::Command;
use std::os::windows::process::CommandExt;
const CREATE_NO_WINDOW: u32 = 0x08000000;
const DETACHED_PROCESS: u32 = 0x00000008;
let mut command = Command::new("cmd").args(&["/C", "start", &exe_path]);
command.creation_flags(DETACHED_PROCESS); // Be careful: This only works on windows
// If you use DETACHED_PROCESS you could set stdout, stderr, and stdin to Stdio::null() to avoid possible allocations.
std:os::windows::process::CommandExt

在为 Windows 构建时使用特定于 Windows 的选项扩展process::Command生成器。在标准库中没有为CREATE_NO_WINDOW定义常量,所以你需要自己定义它或使用0x08000000的原始值:

let command = Command::new("my-command")
.args("param")
.creation_flags(0x08000000)
.spawn();

最新更新