SystemEvents Class
Overview
The SystemEvents class provides notifications of system-wide events. It is a static class that raises events for changes such as display settings, power mode, session switch, user preferences, and more.
Namespace: Microsoft.Win32
Assembly: System.Windows.Forms.dll
Syntax
public static class SystemEvents
{
// Events
public static event EventHandler? DisplaySettingsChanged;
public static event PowerModeChangedEventHandler? PowerModeChanged;
public static event SessionSwitchEventHandler? SessionSwitch;
public static event UserPreferenceChangedEventHandler? UserPreferenceChanged;
// ... many more events
// Methods
public static void SetSuspendState(bool suspend, bool forceCritical, bool disableWakeEvent);
// ... other members
}
Members
| Member | Description |
|---|---|
DisplaySettingsChanged | Occurs when the display settings change. |
PowerModeChanged | Occurs when the user suspends or resumes the system. |
SessionSwitch | Occurs when a user logs on or off, or locks/unlocks the workstation. |
UserPreferenceChanged | Occurs when a system-wide setting changes (e.g., color scheme). |
SetSuspendState(bool suspend, bool forceCritical, bool disableWakeEvent) | Puts the system into suspend or hibernate mode. |
Examples
Subscribe to the PowerModeChanged event to detect when the system is about to sleep or resume:
using Microsoft.Win32;
class Program
{
static void Main()
{
SystemEvents.PowerModeChanged += OnPowerModeChanged;
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
SystemEvents.PowerModeChanged -= OnPowerModeChanged;
}
private static void OnPowerModeChanged(object? sender, PowerModeChangedEventArgs e)
{
switch (e.Mode)
{
case PowerModes.Suspend:
Console.WriteLine("System is suspending...");
break;
case PowerModes.Resume:
Console.WriteLine("System resumed.");
break;
}
}
}