给Windows 服务添加命令行参数(转)
from http://space.itpub.net/100788/viewspace-310262
1. 首先,给服务的Main方法添加参数,判断如果参数为"-s"则运行服务。
static void Main(string[] args)
{
// 运行服务
if (args[0].ToLower() == "/s" || args[0].ToLower() == "-s")
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[] { new MyService1() };
ServiceBase.Run(ServicesToRun);
}
}
{
// 运行服务
if (args[0].ToLower() == "/s" || args[0].ToLower() == "-s")
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[] { new MyService1() };
ServiceBase.Run(ServicesToRun);
}
}
2. 然后,给serviceInstaller1添加AfterInstall事件,修改注册表给服务添加命令行参数。
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
{}
}
{
// 给服务添加命令行参数 -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
{}
}