Click here to Skip to main content
15,881,852 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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.
Posted
Updated 7-Apr-10 11:34am
v2

See here: Detect Shutdown from .NET[^]. This should get you started.
 
Share this answer
 
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);
}
}
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900