这是一个更简单的解决方案,但是,它需要基于WSH 的帮助脚本,runHidden.vbs(见底部):
wscript .\runHidden.vbs bash -c "DISPLAY=:0 xmessage 'hello, world'"
应用@davv 自己的后台启动技术来避免每次都创建一个新的bash 实例:
一次性操作(例如,在启动时):启动一个隐藏的、保持打开的bash 窗口。这会产生 2 bash 进程:Windows bash.exe 进程拥有控制台窗口,以及 WSL bash 进程(由 WSL init 单例拥有),然后可用于服务后台命令。
wscript .\runHidden.vbs bash # hidden helper instance for servicing background commands
对于每个 X Window 启动命令:使用 & 终止每个命令,使其由隐藏的 WSL bash 实例运行异步,不让 invoking bash 实例保持活动状态:
wscript .\runHidden.vbs bash -c "DISPLAY=:0 xmessage 'hello, world' &"
runHidden.vbs源码:
' Simple command-line help.
select case WScript.Arguments(0)
case "-?", "/?", "-h", "--help"
WScript.echo "Usage: runHidden executable [...]" & vbNewLine & vbNewLine & "Runs the specified command hidden (without a visible window)."
WScript.Quit(0)
end select
' Separate the arguments into the executable name
' and a single string containing all arguments.
exe = WScript.Arguments(0)
sep = ""
for i = 1 to WScript.Arguments.Count -1
' Enclose arguments in "..." to preserve their original partitioning.
args = args & sep & """" & WScript.Arguments(i) & """"
sep = " "
next
' Execute the command with its window *hidden* (0)
WScript.CreateObject("Shell.Application").ShellExecute exe, args, "", "open", 0
即使从 GUI 应用程序启动(例如通过使用 Win+R 调用的Run 对话框),也不会显示控制台窗口。
如果您的系统默认配置为使用wscript.exe 执行.vbs 脚本(我认为wscript //h:wscript /s 是默认配置),您可以调用@ 987654341@ 直接,如果你把它放在你的%PATH% 中,仅按文件名(根):runHidden ...。
请注意,该脚本的使用不仅限于控制台应用程序:即使是 GUI 应用程序也可以使用它隐藏运行。