需求:在做程序接口需要托管至服务开机自启动、监听服务等功能的。
入口函数:
using System;
using System.Configuration.Install;
using System.ServiceProcess;
using System.Windows.Forms;
namespace MailServerService {
/// <summary>
/// Application main class.
/// </summary>
public class Program {
#region static method Main
/// <summary>
/// Application main entry point.
/// </summary>
/// <param name="args">Command line argumnets.</param>
public static void Main(string[] args) {
try {
if (args.Length > 0 && args[0].ToLower() == "-install") {
ManagedInstallerClass.InstallHelper(new string[] { "MailServerService.exe" });
ServiceController c = new ServiceController("MiFanMailServer");
c.Start();
} else if (args.Length > 0 && args[0].ToLower() == "-uninstall") {
ManagedInstallerClass.InstallHelper(new string[] { "/u", "MailServerService.exe" });
} else {
ServiceBase[] servicesToRun = new ServiceBase[] { new MailServer_Service() };
ServiceBase.Run(servicesToRun);
}
} catch (Exception e) {
MessageBox.Show("错误: " + e.ToString()+"需要以管理员身份运行!", "温馨提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
#endregion
}
}
例:
using System;
using System.Collections;
using System.ComponentModel;
using System.Configuration.Install;
using System.ServiceProcess;
namespace MailServerService {
[RunInstaller(true)]
public class MailServer_Service_Installer : Installer
{
private System.ComponentModel.Container components = null;
private ServiceInstaller serviceInstaller;
private ServiceProcessInstaller processInstaller;
public MailServer_Service_Installer()
{
processInstaller = new ServiceProcessInstaller();
serviceInstaller = new ServiceInstaller();
processInstaller.Account = ServiceAccount.LocalSystem;
serviceInstaller.StartType = ServiceStartMode.Automatic;
serviceInstaller.ServiceName = "MiFanMailServer";
serviceInstaller.Description = "邮件服务器";
Installers.Add(serviceInstaller);
Installers.Add(processInstaller);
}
}
}
文章评论