Mat*_*vis 181
如果您有任何C/C++/Java背景,那么冒着明显的风险,我认为C#为您提供最低的入口点.
假设您使用的是Visual Studio 2008,则可以按照以下步骤操作:
false阻止事件默认写入应用程序事件日志(注意:我不是说你不应该记录服务事件;我只是想写入我自己的事件日志而不是应用程序日志 - 见下文)true如果要处理系统关闭,则设置为true,则还需要覆盖OnShutdown方法.我在下面创建了一个示例,说明了这些函数的用法.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;
}
}
Run Code Online (Sandbox Code Playgroud)
此时,您可以构建项目以使Windows服务可执行.要安装服务,请打开Visual Studio 2008命令提示符,然后导航到可执行文件所在的Debug或Release目录.在命令提示符下,键入以下内容: InstallUtil ServiceExample.exe.这将在本地计算机上安装您的服务.要卸载它,请在命令提示符处键入以下内容: InstallUtil/u ServiceExample.exe
只要您的服务未运行,您就可以对服务进行更改并重新构建,即您不必卸载服务即可对其进行更改.但是,只要它正在运行,您将无法使用修复程序和增强功能覆盖可执行文件.
要查看您的服务,请打开ServiceExample.cs文件并进行以下更改:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
使用这些更改运行服务后,您可以在事件查看器中查看ServiceExample事件日志,并查看其中记录的消息.
希望这可以帮助.
编辑:如果您更喜欢使用应用程序事件日志来进行事件日志记录而不是自定义事件日志,则只需对ProjectInstaller.cs文件不进行任何更改.此外,省略在ServiceExample构造函数中设置EventLog的Log属性的行.运行服务时,日志消息将显示在应用程序事件日志中.
| 归档时间: |
|
| 查看次数: |
55975 次 |
| 最近记录: |