如何隐藏以 std::process::Command 启动的进程的控制台窗口?

Fre*_*dol 6 windows cmd rust

即使在#![windows_subsystem = "windows"]我的应用程序顶部,使用std::process::Command也会创建一个控制台窗口 0.1 到 0.3 秒。std::process::Command有没有办法隐藏使用?

\n\n

在 C# 中,我可以使用p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;\xe2\x80\x94 Rust 有类似的东西吗?

\n\n

std::process::command创建控制台窗口的示例用法:

\n\n
Command::new("cmd").args(&["/C", "start", &exe_path]);\n
Run Code Online (Sandbox Code Playgroud)\n\n

exePath 是 Windows GUI 应用程序的路径。

\n

Rob*_*ner 5

你可以使用std::os::windows::process::CommandExt::creation_flags. 请参阅进程创建标志的文档页面。

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

我还建议使用startas 命令,因为否则您将不得不使用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.
Run Code Online (Sandbox Code Playgroud)