diff --git a/Apewer.Windows/WinForm/Tray.cs b/Apewer.Windows/WinForm/Tray.cs index 436e3fd..5580d84 100644 --- a/Apewer.Windows/WinForm/Tray.cs +++ b/Apewer.Windows/WinForm/Tray.cs @@ -354,31 +354,10 @@ namespace Apewer.WinForm public static void Service(Action onStart, Action onStop = null) { var processName = Process.GetCurrentProcess().ProcessName; - var service = new TrayService(processName, onStart, onStop); + var service = new WindowsService(processName, onStart, onStop); ServiceBase.Run(service); } - class TrayService : ServiceBase - { - - Action on_start; - Action on_stop; - - public TrayService(string serviceName, Action onStart, Action onStop) - { - if (serviceName.IsEmpty()) throw new ArgumentNullException(nameof(serviceName)); - if (onStart == null) throw new ArgumentNullException(nameof(onStart)); - ServiceName = serviceName; - on_start = onStart; - on_stop = onStop; - } - - protected override void OnStart(string[] args) => RuntimeUtility.InBackground(on_start); - - protected override void OnStop() => on_stop?.Invoke(); - - } - #endregion } diff --git a/Apewer.Windows/WinForm/WindowsService.cs b/Apewer.Windows/WinForm/WindowsService.cs new file mode 100644 index 0000000..108d98c --- /dev/null +++ b/Apewer.Windows/WinForm/WindowsService.cs @@ -0,0 +1,66 @@ +using Apewer.Internals.Interop; +using System; +using System.Diagnostics; +using System.ServiceProcess; + +namespace Apewer.WinForm +{ + + /// Windows 服务。 + public class WindowsService : ServiceBase + { + + Action on_start = null; + Action on_stop = null; + + /// 创建 Windows 服务实例。 + /// 服务名称。 + /// 服务启动后,在后台线程执行的程序。 + /// 服务停止前,同步执行的程序。 + /// + /// + public WindowsService(string serviceName, Action onStart, Action onStop) + { + if (serviceName.IsEmpty()) throw new ArgumentNullException(nameof(serviceName)); + + ServiceName = serviceName; + on_start = onStart; + on_stop = onStop; + } + + /// 创建 Windows 服务实例。 + /// 默认使用当前进程名称作为服务名称。 + /// 服务启动后,在后台线程执行的程序。 + /// 服务停止前,同步执行的程序。 + /// + public WindowsService(Action onStart, Action onStop) : this(Process.GetCurrentProcess().ProcessName, onStart, onStop) { } + + /// 服务启动时执行的程序。 + protected override void OnStart(string[] args) => RuntimeUtility.InBackground(on_start); + + /// 服务停止时执行的程序。 + protected override void OnStop() => on_stop?.Invoke(); + + /// 启动 Windows 服务实例。 + /// 服务名称。 + /// 服务启动后,在后台线程执行的程序。 + /// 服务停止前,同步执行的程序。 + /// + /// + public static WindowsService Run(string serviceName, Action onStart, Action onStop = null) + { + var service = new WindowsService(serviceName, onStart, onStop); + ServiceBase.Run(service); + return service; + } + + /// 启动 Windows 服务实例。 + /// 默认使用当前进程名称作为服务名称。 + /// 服务启动后,在后台线程执行的程序。 + /// 服务停止前,同步执行的程序。 + /// + public static WindowsService Run(Action onStart, Action onStop = null) => Run(Process.GetCurrentProcess().ProcessName, onStart, onStop); + + } + +}