我想提供一种在您开始或停止使用计算机时都写入.txt文件的服务。它可以检测到计算机关机,但不能检测到睡眠或唤醒。
这是我使用的代码:
public Service1()
{
InitializeComponent();
Microsoft.Win32.SystemEvents.SessionEnded += new Microsoft.Win32.SessionEndedEventHandler(SystemEvents_SessionEnded);
SystemEvents.PowerModeChanged += OnPowerChange;
CanHandlePowerEvent = true;
}
protected virtual bool OnPowerEvent(System.ServiceProcess.PowerBroadcastStatus powerStatus)
{
if (powerStatus == PowerBroadcastStatus.QuerySuspend || powerStatus == PowerBroadcastStatus.Suspend)
{
WriteToFile("computer turned off at : " + DateTime.Now);
return false;
}
else if (powerStatus == PowerBroadcastStatus.ResumeCritical || powerStatus == PowerBroadcastStatus.ResumeSuspend || powerStatus == PowerBroadcastStatus.ResumeAutomatic)
{
WriteToFile("computer turned on at : " + DateTime.Now);
return true;
}
return true;
}
private void OnPowerChange(object s, PowerModeChangedEventArgs e)
{
switch (e.Mode)
{
case PowerModes.Resume:
WriteToFile("computer turned on at : " + DateTime.Now);
break;
case PowerModes.Suspend:
WriteToFile("computer turned off at : " + DateTime.Now);
break;
}
}
我将不胜感激。
注意:WriteToFile是用于写入.txt文件的自定义方法
您可以在HiddenForm
的帮助下使用它。所需的更改是:
第一:即使说PowerModeChanged
,也要订阅[C0
HiddenForm_Load
第二:使用以下线程启动消息泵:
private void HiddenForm_Load(object sender, EventArgs e)
{
SystemEvents.PowerModeChanged += new PowerModeChangedEventHandler(OnPowerChange);
}
第三:在属性页的protected override void OnStart(string[] args)
{
//DO work needed in OnStart
// Message Pump will run in separate thread
new Thread(ThreadWork.RunMessagePump).Start();
}
//Thread class to RunMessagePump
public class ThreadWork
{
public static void RunMessagePump()
{
Application.Run(new HiddenForm());
}
}
选项卡中选中“允许服务与桌面交互”复选框。
示例参考位于Log On