Jan Remunda Jan Remunda - 1 year ago 169
C# Question

Get Windows Server shutdown reason in C#

Is it possible to get shutdown reason in Windows Server 2008 immediately after user choose the reason in dialog window? For the shutdown event I'm using SystemEvents.SessionEnding.
I want to write windows service, which will send e-mail about this event.

Or is there any other way in windows server to send e-mails about shutdown/restart event with getting the reason entered by user? Also, I want to notify about power source change (electic line/battery), but this I have already solved by Kernel32.dll > GetSystemPowerStatus.

Answer Source

You can get the shutdown reason inspecting the EventLog.

I assembled a quick demo on Windows Forms that you can adapt to your Windows service.

I've added a EventLog component to the Form and configured it properly. The snippet below shows the code generated in InitializeComponent() for the settings I've maid through the designer.

this.eventLog1.EnableRaisingEvents = true;
this.eventLog1.Log = "System";
this.eventLog1.Source = "USER32";
this.eventLog1.SynchronizingObject = this;
this.eventLog1.EntryWritten += new System.Diagnostics.EntryWrittenEventHandler(this.eventLog1_EntryWritten);

On the event handler, you'll have something along the following lines:

private void eventLog1_EntryWritten(object sender, System.Diagnostics.EntryWrittenEventArgs e)
    EventLogEntry entry = e.Entry;
    if (e.Entry.EventID == 1074)
        File.AppendAllText(@"c:\message.txt", entry.Message);

Take a look at your event log to see the appropriate EventIds to filter out.

The compiler will warn you about EventID being deprecated and telling you that you should use InstanceId, but in the quick tests I've done here, it didn't write to my log file and I think we already have enough information to put you on track.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download