Ich habe versucht, den Sitzungsschalter zu abonnieren. Es wird erfolgreich abonniert. Aber das Ereignis löst nicht aus. < /P>
Code: Select all
using System;
using System.Diagnostics;
using System.IO;
using System.ServiceProcess;
using System.Timers;
using Microsoft.Win32;
namespace MyFirstService
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
WriteToFile("Service is started at " + DateTime.Now);
// Subscribe to session switch events
Microsoft.Win32.SystemEvents.SessionSwitch += new Microsoft.Win32.SessionSwitchEventHandler(SystemEvents_SessionSwitch);
}
protected override void OnStop()
{
WriteToFile("Service is stopped at " + DateTime.Now);
// Unsubscribe from session switch events
SystemEvents.SessionSwitch -= SystemEvents_SessionSwitch;
}
void SystemEvents_SessionSwitch(object sender, Microsoft.Win32.SessionSwitchEventArgs e)
{
WriteToFile("Event Triggered");
if (e.Reason == SessionSwitchReason.SessionLock)
{
WriteToFile("System Locked" + DateTime.Now);
}
else if (e.Reason == SessionSwitchReason.SessionUnlock)
{
WriteToFile("System UnLocked" + DateTime.Now);
}
}
public void WriteToFile(string Message)
{
try
{
string path = AppDomain.CurrentDomain.BaseDirectory + "\\Logs";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string filepath = Path.Combine(path, "ServiceLog_" + DateTime.Now.Date.ToShortDateString().Replace('/', '_') + ".txt");
using (StreamWriter sw = File.AppendText(filepath))
{
sw.WriteLine($"{DateTime.Now}: {Message}");
}
}
catch (Exception ex)
{
// Handle exceptions (e.g., file access issues)
EventLog.WriteEntry("Application", $"Failed to write to log file: {ex.Message}", EventLogEntryType.Error);
}
}
}
}