3

开机启动并隐藏 cmd 窗口程序在后台运行 - winsw 使用教程

 3 years ago
source link: https://cjh0613.com/20200504win-exe-service.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

开机启动并隐藏 cmd 窗口程序在后台运行 - winsw 使用教程

发表2020-05-04更新2020-08-01字数837预计阅读时长5分阅读次数117

Windows 下手动添加开机启动的方式一般是创建快捷方式到启动文件夹,但某些程序是命令行式运行的,打开后会显示一个 cmd 窗口,而且窗口关闭程序就会停止。而 winsw 可以将 Win­dows 上的任一程序注册为服务,实现命令行程序开机启动和后台运行。

下载 winsw

从项目仓库的 release 页面下载,有 .NET2 和 .NET4 两个版本,Win­dows 10 建议下载 .NET4 版本。为了便于理解和方便后续的操作,下载后建议重命名为 winsw.exe

编写配置文件

官方提供了一个配置文件模版,里面有所有配置项和详细的注释。对于简单的使用不需要那么复杂:

<configuration>
<id>myapp</id>
<name>MyApp Service (powered by WinSW)</name>
<description>This service is a service cratead from a sample configuration</description>
<executable>%BASE%\myExecutable.exe</executable>
<arguments>-classpath c:\cygwin\home\kohsuke\ws\hello-world\out\production\hello-world test.Main</arguments>
<log mode="append"></log>
</configuration>

配置项说明:

  • id - 服务的ID。必须在所有服务中是唯一的,由字母数字字符组成。
  • name - 服务的显示名称。可以和id一样,也需要在所有服务中是唯一的,可以包含空格和其他字符。
  • description - 描述。随便写,自己明白就行,或者不写也行。
  • executable - 可以是程序文件名,也可以是绝对路径。推荐放和程序在一起,直接写文件名就行。
  • arguments - 程序的启动参数,有就写,没有就删除。
  • log mode - 日志模式。默认是追加模式(append),即无限制写入。如果不想让日志变得无限大建议设置为reset。不需要日志则设置为none

创建一个与 winsw 程序本体名称一致的.xml 后缀的空白文档,如果 winsw 程序本体是 winsw.exe,那么配置文件命名为 winsw.xml,放在一起,然后把上面的内容复制进去,然后按需求进行修改。

下面是某个配置文件:

<configuration>
<id>UnblockNeteaseMusic</id>
<name>UnblockNeteaseMusic</name>
<description>UnblockNeteaseMusic Background Service</description>
<executable>UnblockNeteaseMusic.bat</executable>
<log mode="reset"></log>
</configuration>

写完配置文件,确定程序和 winsw.exewinsw.xml 在同一路径下,在这个路径以管理员权限打开 cmd 或者 Powershell ,输入 winsw.exe install ,如果不出意外,只会输出一条信息:

INFO  - Installing the service with id 'UnblockNeteaseMusic'

UnblockNeteaseMusic 这里的字符应该是你自己写的程序的 id ,这里仅用于演示。

输入 winsw.exe start 启动服务,这样程序就在后台无窗口运行了,重启开机也会无窗口自动启动。停止运行则输入 winsw.exe stop。你也可以在 Win­dows 的任务管理器或者服务中管理这个程序的服务。

如果不再需要这个服务,先停止服务,然后输入 winsw.exe uninstall 即可卸载服务。

https://p3terx.com/archives/boot-and-hide-the-cmd-window-program-to-run-in-the-background-winsw-tutorial.html


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK