Windows系统关闭时在服务中执行功能. [英] Execute function in service when Windows system shuts down.

查看:117
本文介绍了Windows系统关闭时在服务中执行功能.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当计算机关闭或重新启动时,我需要在服务中执行功能. On_Stop不起作用,因为只有在手动关闭该服务后,该功能才起作用.

我看了SystemEvents.SessionEnding,但这似乎只能在Windows窗体的上下文中工作.我还需要它能够在登录屏幕上检测到关闭事件,并且Windows窗体在登录屏幕上下文中不起作用.

I need to execute a function in my service when the computer shuts down or restarts. On_Stop doesn''t work, because that only seems to function if the service is shut down manually.

I have looked at SystemEvents.SessionEnding, but that only seems to work within the context of a Windows form. I need this to be able to detect shutdown events at the login screen as well, and Windows forms don''t work in the login screen context.

推荐答案

请参阅此处:从.NET检测关闭 [
See here: Detect Shutdown from .NET[^]. This should get you started.


最后找到了一个很好的例子.
http://msdn.microsoft.com/en-us/library/microsoft.win32. systemevents.aspx [ ^ ]

服务没有消息循环,除非允许它们与桌面交互.如果未通过隐藏表单提供消息循环(如本例所示),则该服务必须在本地系统帐户下运行,并且需要手动干预才能与桌面进行交互.也就是说,管理员必须在服务属性对话框的登录"选项卡上手动选中允许服务与桌面交互"复选框.在这种情况下,将自动提供消息循环.仅当服务在本地系统帐户下运行时,此选项才可用.无法通过编程方式启用与桌面的交互.

本示例中的服务启动了一个运行HiddenForm实例的线程.这些事件以表格形式进行连接和处理.必须将事件连接到表单的load事件中,以确保首先完全加载表单.否则将不会引发事件.

使用系统;
使用System.ServiceProcess;
使用System.Threading;
使用System.Windows.Forms;
使用System.Diagnostics;
使用Microsoft.Win32;
使用System.ComponentModel;
使用System.Configuration.Install;

命名空间SimpleServiceCs
{
公共类SimpleService:ServiceBase
{
静态void Main(string [] args)
{
ServiceBase.Run(new SimpleService());
}

受保护的重写void OnStart(string [] args)
{
EventLog.WriteEntry("SimpleService",启动SimpleService");
新线程(RunMessagePump).Start();
}

void RunMessagePump()
{
EventLog.WriteEntry("SimpleService.MessagePump",正在启动SimpleService消息泵");
Application.Run(new HiddenForm());
}

受保护的重写void OnStop()
{
Application.Exit();
}
}

公共局部类HiddenForm:Form
{
公共HiddenForm()
{
InitializeComponent();
}

私有无效HiddenForm_Load(对象发送者,EventArgs e)
{
SystemEvents.TimeChanged + =新的EventHandler(SystemEvents_TimeChanged);
SystemEvents.UserPreferenceChanged + =新的UserPreferenceChangedEventHandler(SystemEvents_UPCChanged);
}

私有无效HiddenForm_FormClosing(对象发送者,FormClosingEventArgs e)
{
SystemEvents.TimeChanged-=新的EventHandler(SystemEvents_TimeChanged);
SystemEvents.UserPreferenceChanged-=新的UserPreferenceChangedEventHandler(SystemEvents_UPCChanged);
}

私有void SystemEvents_TimeChanged(对象发送者,EventArgs e)
{
EventLog.WriteEntry("SimpleService.TimeChanged",时间已更改;现在为" +
DateTime.Now.ToLongTimeString());
}

私有void SystemEvents_UPCChanged(对象发送者,UserPreferenceChangedEventArgs e)
{
EventLog.WriteEntry("SimpleService.UserPreferenceChanged",e.Category.ToString());
}
}

局部类HiddenForm
{
私有System.ComponentModel.IContainer组件= null;

受保护的重写void Dispose(布尔处置)
{
if(处理&&(组件!= null))
{
components.Dispose();
}
base.Dispose(处置);
}

私有void InitializeComponent()
{
this.SuspendLayout();
this.AutoScaleDimensions = new System.Drawing.SizeF(6F,13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(0,0);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.Name ="HiddenForm";
this.Text ="HiddenForm";
this.WindowState = System.Windows.Forms.FormWindowState.Minimized;
this.Load + =新的System.EventHandler(this.HiddenForm_Load);
this.FormClosing + =新的System.Windows.Forms.FormClosingEventHandler(this.HiddenForm_FormClosing);
this.ResumeLayout(false);

}
}

[RunInstaller(true)]
公共类SimpleInstaller:安装程序
{
私有ServiceInstaller serviceInstaller;
私有ServiceProcessInstaller processInstaller;

公共SimpleInstaller()
{
processInstaller =新的ServiceProcessInstaller();
serviceInstaller =新的ServiceInstaller();

//服务将在系统帐户下运行
processInstaller.Account = ServiceAccount.LocalSystem;

//服务将具有手册的开始类型
serviceInstaller.StartType = ServiceStartMode.Automatic;

serviceInstaller.ServiceName =简单服务";

Installers.Add(serviceInstaller);
Installers.Add(processInstaller);
}
}
}
Finally found a good example.
http://msdn.microsoft.com/en-us/library/microsoft.win32.systemevents.aspx[^]

Services do not have message loops, unless they are allowed to interact with the desktop. If the message loop is not provided by a hidden form, as in this example, the service must be run under the local system account, and manual intervention is required to enable interaction with the desktop. That is, the administrator must manually check the Allow service to interact with desktop check box on the Log On tab of the service properties dialog box. In that case, a message loop is automatically provided. This option is available only when the service is run under the local system account. Interaction with the desktop cannot be enabled programmatically.

The service in this example starts a thread that runs an instance of HiddenForm. The events are hooked up and handled in the form. The events must be hooked up in the load event of the form, to make sure that the form is completely loaded first; otherwise the events will not be raised.

using System;
using System.ServiceProcess;
using System.Threading;
using System.Windows.Forms;
using System.Diagnostics;
using Microsoft.Win32;
using System.ComponentModel;
using System.Configuration.Install;

namespace SimpleServiceCs
{
public class SimpleService : ServiceBase
{
static void Main(string[] args)
{
ServiceBase.Run(new SimpleService());
}

protected override void OnStart(string[] args)
{
EventLog.WriteEntry("SimpleService", "Starting SimpleService");
new Thread(RunMessagePump).Start();
}

void RunMessagePump()
{
EventLog.WriteEntry("SimpleService.MessagePump", "Starting SimpleService Message Pump");
Application.Run(new HiddenForm());
}

protected override void OnStop()
{
Application.Exit();
}
}

public partial class HiddenForm : Form
{
public HiddenForm()
{
InitializeComponent();
}

private void HiddenForm_Load(object sender, EventArgs e)
{
SystemEvents.TimeChanged += new EventHandler(SystemEvents_TimeChanged);
SystemEvents.UserPreferenceChanged += new UserPreferenceChangedEventHandler(SystemEvents_UPCChanged);
}

private void HiddenForm_FormClosing(object sender, FormClosingEventArgs e)
{
SystemEvents.TimeChanged -= new EventHandler(SystemEvents_TimeChanged);
SystemEvents.UserPreferenceChanged -= new UserPreferenceChangedEventHandler(SystemEvents_UPCChanged);
}

private void SystemEvents_TimeChanged(object sender, EventArgs e)
{
EventLog.WriteEntry("SimpleService.TimeChanged", "Time changed; it is now " +
DateTime.Now.ToLongTimeString());
}

private void SystemEvents_UPCChanged(object sender, UserPreferenceChangedEventArgs e)
{
EventLog.WriteEntry("SimpleService.UserPreferenceChanged", e.Category.ToString());
}
}

partial class HiddenForm
{
private System.ComponentModel.IContainer components = null;

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

private void InitializeComponent()
{
this.SuspendLayout();
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(0, 0);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.Name = "HiddenForm";
this.Text = "HiddenForm";
this.WindowState = System.Windows.Forms.FormWindowState.Minimized;
this.Load += new System.EventHandler(this.HiddenForm_Load);
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.HiddenForm_FormClosing);
this.ResumeLayout(false);

}
}

[RunInstaller(true)]
public class SimpleInstaller : Installer
{
private ServiceInstaller serviceInstaller;
private ServiceProcessInstaller processInstaller;

public SimpleInstaller()
{
processInstaller = new ServiceProcessInstaller();
serviceInstaller = new ServiceInstaller();

// Service will run under system account
processInstaller.Account = ServiceAccount.LocalSystem;

// Service will have Start Type of Manual
serviceInstaller.StartType = ServiceStartMode.Automatic;

serviceInstaller.ServiceName = "Simple Service";

Installers.Add(serviceInstaller);
Installers.Add(processInstaller);
}
}
}


这篇关于Windows系统关闭时在服务中执行功能.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆