C# - 是否可以将单个.exe操作作为应用程序(单击时)或服务(由Windows运行时)

ben*_*rre 1 c# service window

是否可以将应用程序作为服务运行,如果它是这样注册的,但如果双击它只是启动一个常规的交互式应用程序?

Chr*_*ken 5

是.您可以使用该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);
            }
Run Code Online (Sandbox Code Playgroud)

包装类(确保扩展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);
    }
}
Run Code Online (Sandbox Code Playgroud)