C#,将WinForm改成Service

1、添加引用:System.ServiceProcess
2、建类:

class ServiceProc : ServiceBase
{
    MainService ms = new MainService();

    public ServiceProc()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        ms.NoticeEvent += Ms_NoticeEvent;
        ms.Start();
    }

    private void Ms_NoticeEvent(string type, string content, CommunalClass.Entities.LogLevels level)
    {
        LogsRecord.Write("INFO", $"[{DateTime.Now.ToString("mm:ss")}][type]{content}");
    }

    protected override void OnStop()
    {
        ms.Stop();
        Environment.Exit(Environment.ExitCode);
    }

    private System.ComponentModel.IContainer components = null;

    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

    private void InitializeComponent()
    {
        components = new System.ComponentModel.Container();
        this.ServiceName = "SystemMonitorService";
    }
}

3、右键点击刚刚建的类,查看设计器,在设计界面上,右健,“添加安装程序”;
4、新的安装类上,会自动添加2个组件:serviceProcessInstaller1、serviceInstaller1;
5、serviceProcessInstaller1 属性:Account,改成 LocalSystem;
6、serviceInstaller1 属性:Description 描述,DisplayName 显示在服务中的名字,StartType 改成 Automatic 自动启动;
7、配置文件中加一项:run_as_service,用来配置是否以服务的方式启动程序,这样可以方便的以后随时用WINFORM方式启动;
8、改 Program.cs:

/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
    Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
    AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    if (AppSet.Default.run_as_service)
    {
        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[] { new ServiceProc() };
        ServiceBase.Run(ServicesToRun);
    }
    else
        Application.Run(new Form1());
}

static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
    try { trip.CommunalClass.LogsRecord.write("AppDomainError", e.ExceptionObject.ToString()); }
    catch { }
}

static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
    try { trip.CommunalClass.LogsRecord.write("AppError", e.Exception.ToString()); }
    catch { }
}

9、此时大功告成,再就是写几个批处理文件:

-------------- 安装:service_install.bat --------------

@echo off 
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe myapp.exe
pause

-------------- 卸载:service_uninstall.bat --------------

@echo off 
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe /u myapp.exe
pause

-------------- 开始:service_start.bat --------------

@echo off 
net start ServiceName
pause

-------------- 停止:service_stop.bat --------------

@echo off 
net stop ServiceName
pause

标签: none

添加新评论