使用Windows API,我们可以启动新进程,控制台应用程序,并隐藏其“黑色”窗口。这可以在进程创建时完成,并避免完全显示“黑色”窗口。
在
CreateProcess函数中,
dwCreationFlags
参数可以具有
CREATE_NO_WINDOW标志:
The process is a console application that is being run
without a console window. Therefore, the console handle
for the application is not set. This flag is ignored if
the application is not a console application
这是使用该方法的
hide-win32-console-window可执行文件和
源代码链接。
hide-win32-console-window
类似于
Jamesdlin的silentbatch程序。
有一个未解决的问题:
当程序窗口不存在时,该怎么处理程序输出?如果发生异常怎么办?抛弃输出不是一个好的解决方案。
hide-win32-console-window
使用匿名管道将程序的输出重定向到当前目录中创建的文件中。
用法
batchscript_starter.exe full/path/to/application [arguments to pass on]
运行Python脚本的示例
batchscript_starter.exe c:\Python27\python.exe -c "import time; print('prog start'); time.sleep(3.0); print('prog end');"
输出文件将在工作目录中创建,名称为
python.2019-05-13-13-32-39.log
,其中包含来自Python命令的输出:
prog start
prog end
运行命令示例
batchscript_starter.exe C:\WINDOWS\system32\cmd.exe /C dir .
输出文件将被创建在工作目录中,命名为cmd.2019-05-13-13-37-28.log
,其中包含来自CMD的输出:
Volume in drive Z is Storage
Volume Serial Number is XXXX-YYYY
Directory of hide_console_project\hide-win32-console-window
2019-05-13 13:37 <DIR> .
2019-05-13 13:37 <DIR> ..
2019-05-13 04:41 17,274 batchscript_starter.cpp
2018-04-10 01:08 46,227 batchscript_starter.ico
2019-05-12 11:27 7,042 batchscript_starter.rc
2019-05-12 11:27 1,451 batchscript_starter.sln
2019-05-12 21:51 8,943 batchscript_starter.vcxproj
2019-05-12 21:51 1,664 batchscript_starter.vcxproj.filters
2019-05-13 03:38 1,736 batchscript_starter.vcxproj.user
2019-05-13 13:37 0 cmd.2019-05-13-13-37-28.log
2019-05-13 04:34 1,518 LICENSE
2019-05-13 13:32 22 python.2019-05-13-13-32-39.log
2019-05-13 04:55 82 README.md
2019-05-13 04:44 1,562 Resource.h
2018-04-10 01:08 46,227 small.ico
2019-05-13 04:44 630 targetver.h
2019-05-13 04:57 <DIR> x64
14 File(s) 134,378 bytes
3 Dir(s) ???,???,692,992 bytes free
运行.bat脚本的示例快捷方式
![Shortcut for starting windowless .bat file](https://istack.dev59.com/MRzAP.webp)
目标
字段:
C:\batchscript_starter.exe C:\WINDOWS\system32\cmd.exe /C C:\start_wiki.bat
Start in
字段指定的目录将保存输出文件。