3 回答
TA贡献1842条经验 获得超13个赞
打开VisualStudio 2008,并选择FilesNewNewProject菜单选项。 在“新项目”对话框中.。 在项目类型中选择VisualC#000-Windows节点 选择WindowsService模板 输入项目的名称和位置 按OK 此时,您已经掌握了Windows服务的所有基础知识。cs文件包含服务的main()方法,Service1.cs定义System.ServiceProcess.ServiceBase组件,这是新的Windows服务。 在Service1组件的属性网格中,考虑至少设置以下属性: (名称)-给你的对象一个直观的名称,例如,Service示例 Autolog-设置为 false为了防止事件默认地写入应用程序事件日志(注意:我不是说您不应该记录服务事件;我只是更喜欢编写自己的事件日志而不是应用程序日志-请参见下面) 倒计时-设置为 true如果您想处理系统关闭 ServiceName-定义服务控制管理器(SCM)将知道您的服务的名称 在ServiceExsquare的代码中,将删除OnStart()和OnStop()虚拟函数。显然,您需要用任何您的服务需要做的事情来填充这些内容。如果将“倒计时”属性更改为 true,您也需要重写OnShu倒计时方法。我在下面创建了一个示例,说明这些函数的使用情况。 此时,ServiceExmen服务基本上已经完成,但是您仍然需要一种方法来安装它。为此,请在设计器中打开ServiceExmen组件。右键单击“设计器”面板中的任何位置,并选择“添加安装程序”菜单选项。这将向项目添加一个ProjectInstaller组件,该组件包含两个附加组件-serviceProcessInstaller1和serviceInstaller1。 在设计器中选择serviceProcessInstaller1组件。在属性网格中,考虑设置以下属性: (Name)-给对象一个直观的名称,例如serviceProcessInstaller 帐户-至少选择LocalService帐户,但如果服务需要更多特权,则可能必须使用NetworkService或LocalSystem帐户 在设计器中选择serviceInstaller1组件。在属性网格中,考虑设置以下属性: (名称)-给对象一个直观的名称,例如serviceInstaller 描述-该服务的描述将显示在您的服务的SCM中 DisplayName-您的服务的友好名称,它将显示在您的服务的SCM中 ServiceName-确保这是您为ServiceExfacum组件的ServiceName属性选择的相同名称(请参见步骤4) StartType-指示您希望服务是自动启动还是手动启动 请记住,我说过我更喜欢编写事件而不是自己的事件日志,而不是应用程序事件日志。为此,需要将ProjectInstaller中的默认EventLogInstaller替换为自定义的EventLogInstaller。使ProjectInstaller的代码如下所示:
using System.Diagnostics;
[RunInstaller(true)]
public partial class ProjectInstaller : Installer
{
public ProjectInstaller()
{
InitializeComponent();
EventLogInstaller installer = FindInstaller(this.Installers);
if (installer != null)
{
installer.Log = "ServiceExample"; // enter your event log name here
}
}
private EventLogInstaller FindInstaller(InstallerCollection installers)
{
foreach (Installer installer in installers)
{
if (installer is EventLogInstaller)
{
return (EventLogInstaller)installer;
}
EventLogInstaller eventLogInstaller = FindInstaller(installer.Installers);
if (eventLogInstaller != null)
{
return eventLogInstaller;
}
}
return null;
}
}using System.Diagnostics;
public partial class ServiceExample : ServiceBase
{
public ServiceExample()
{
// Uncomment this line to debug the service.
//Debugger.Break();
InitializeComponent();
// Ties the EventLog member of the ServiceBase base class to the
// ServiceExample event log created when the service was installed.
EventLog.Log = "ServiceExample";
}
protected override void OnStart(string[] args)
{
EventLog.WriteEntry("The service was started successfully.", EventLogEntryType.Information);
}
protected override void OnStop()
{
EventLog.WriteEntry("The service was stopped successfully.", EventLogEntryType.Information);
}
protected override void OnShutdown()
{
EventLog.WriteEntry("The service was shutdown successfully", EventLogEntryType.Information);
}
}TA贡献2065条经验 获得超14个赞
TA贡献1906条经验 获得超3个赞
- 3 回答
- 0 关注
- 664 浏览
添加回答
举报
