C# - 是否可以让单个 .exe 充当应用程序(单击时)或服务(当 运行 by windows 时)
C# - Is it possible to have a single .exe act as an application (when clicked) or a service (when run by windows)
是否可以让一个应用程序作为服务运行,如果它被注册为服务,但如果双击它只是启动一个常规的交互式应用程序?
是的。您可以使用 Environment.UserInteractive
变量。您需要围绕您的服务创建一个小包装器以公开 OnStart() 和 OnStop() 方法,因为它们是受保护的。
var service = new MyService();
if (Environment.UserInteractive)
{
service.Start(args);
Console.WriteLine("Press any key to stop program");
Console.Read();
service.Stop();
}
else
{
ServiceBase.Run(service);
}
Wrapper Class(确保扩展 ServiceBase
)
public partial class MyService : ServiceBase
{
protected override void OnStart(string[] args)
{
//start code
}
protected override void OnStop()
{
//stopcode
}
public void Start(string[] args)
{
OnStart(args);
}
}
是否可以让一个应用程序作为服务运行,如果它被注册为服务,但如果双击它只是启动一个常规的交互式应用程序?
是的。您可以使用 Environment.UserInteractive
变量。您需要围绕您的服务创建一个小包装器以公开 OnStart() 和 OnStop() 方法,因为它们是受保护的。
var service = new MyService();
if (Environment.UserInteractive)
{
service.Start(args);
Console.WriteLine("Press any key to stop program");
Console.Read();
service.Stop();
}
else
{
ServiceBase.Run(service);
}
Wrapper Class(确保扩展 ServiceBase
)
public partial class MyService : ServiceBase
{
protected override void OnStart(string[] args)
{
//start code
}
protected override void OnStop()
{
//stopcode
}
public void Start(string[] args)
{
OnStart(args);
}
}