【IT168技术文档】
首先,给服务的Main方法添加参数,判断如果参数为"-s"则运行服务。
然后,给 serviceInstaller1 添加 AfterInstall 事件,修改注册表给服务添加命令行参数。static void Main(string[] args) { // 运行服务 if (args[0].ToLower() == "/s" || args[0].ToLower() == "-s") { ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new MyService1() }; ServiceBase.Run(ServicesToRun); } }
private void ServiceInstaller1_AfterInstall(object sender, InstallEventArgs e) { // 给服务添加命令行参数 -s try { RegistryKey regKey = Registry.LocalMachine.OpenSubKey (@"SYSTEM\CurrentControlSet\Services\" + serviceInstaller1.ServiceName, true); object value = regKey.GetValue("ImagePath"); if (value != null) { string imagePath = value.ToString(); regKey.SetValue("ImagePath", imagePath + " -s"); regKey.Flush(); } regKey.Close(); } catch {} }