Edit

Share via


SystemEvents Class

Definition

Provides access to system event notifications. This class cannot be inherited.

C#
public sealed class SystemEvents
Inheritance
SystemEvents

Examples

This section contains two examples. The first example shows how to use system events in an ordinary application, and the second example shows how to use system events in a Windows service.

Example 1

The following code example registers interest in some system events and then waits for any of those events to occur. The output shown occurs if the user changes the display resolution.

C#
using System;
using Microsoft.Win32;

public sealed class App 
{
    static void Main() 
    {         
        // Set the SystemEvents class to receive event notification when a user 
        // preference changes, the palette changes, or when display settings change.
        SystemEvents.UserPreferenceChanging += new 
            UserPreferenceChangingEventHandler(SystemEvents_UserPreferenceChanging);
        SystemEvents.PaletteChanged += new 
            EventHandler(SystemEvents_PaletteChanged);
        SystemEvents.DisplaySettingsChanged += new 
            EventHandler(SystemEvents_DisplaySettingsChanged);        

        // For demonstration purposes, this application sits idle waiting for events.
        Console.WriteLine("This application is waiting for system events.");
        Console.WriteLine("Press <Enter> to terminate this application.");
        Console.ReadLine();
    }

    // This method is called when a user preference changes.
    static void SystemEvents_UserPreferenceChanging(object sender, UserPreferenceChangingEventArgs e) 
    {
        Console.WriteLine("The user preference is changing. Category={0}", e.Category);
    }

    // This method is called when the palette changes.
    static void SystemEvents_PaletteChanged(object sender, EventArgs e)
    {
        Console.WriteLine("The palette changed.");
    }

    // This method is called when the display settings change.
    static void SystemEvents_DisplaySettingsChanged(object sender, EventArgs e)
    {
        Console.WriteLine("The display settings changed.");
    }
}

// This code produces the following output.
// 
//  This app is waiting for system events.
//  Press <Enter> to terminate this application.
//  Display Settings changed.
//  User preference is changing. Category=General

Example 2

The following code example demonstrates a very simple Windows service that handles the TimeChanged and UserPreferenceChanged events. The example includes a service named SimpleService, a form named HiddenForm, and an installer. The form provides the message loop that is required by system events.

Note

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.

Note

The example provides all the necessary code, including the form initialization code typically generated by Visual Studio designers. If you are developing your service in Visual Studio, you can omit the second partial class and use the Properties window to set the height and width of the hidden form to zero, the border style to FormBorderStyle.None, and the window state to FormWindowState.Minimized.

To run the example:

  1. Compile the code from the command line. The name that you use for the source file is not important.

  2. Install the service from the command line using the Installutil.exe (Installer Tool) utility. For example, InstallUtil example.exe if the source file name is example.cs or example.vb. You must be an administrator to install the service.

  3. Use the Services console to start the service.

  4. Change the system time, or change user preferences, such as mouse properties.

  5. View the messages in the Application category of Event Viewer.

  6. Use the Services console to stop the service.

  7. Uninstall the service from the command line by using the /u option. For example, InstallUtil /u example.exe.

C#
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);
        }
    }
}

Remarks

The SystemEvents class provides the ability to respond to specific types of system events.

When a system event is raised, any delegates attached to the event are called using the thread that monitors for system events. Therefore, you should make any calls from your event handlers thread-safe. If you need to call a system event that is not exposed as a member of this class, you can use the InvokeOnEventsThread method.

Caution

Do not perform time-consuming processing on the thread that raises a system event handler because it might prevent other applications from functioning.

Note

Some system events might not be raised on Windows Vista. Be sure to verify that your application works as expected on Windows Vista.

Methods

CreateTimer(Int32)

Creates a new window timer associated with the system events window.

Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetType()

Gets the Type of the current instance.

(Inherited from Object)
InvokeOnEventsThread(Delegate)

Invokes the specified delegate using the thread that listens for system events.

KillTimer(IntPtr)

Terminates the timer specified by the given id.

MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
ToString()

Returns a string that represents the current object.

(Inherited from Object)

Events

DisplaySettingsChanged

Occurs when the user changes the display settings.

DisplaySettingsChanging

Occurs when the display settings are changing.

EventsThreadShutdown
Obsolete.

Occurs before the thread that listens for system events is terminated.

InstalledFontsChanged

Occurs when the user adds fonts to or removes fonts from the system.

LowMemory
Obsolete.
Obsolete.
Obsolete.

Occurs when the system is running out of available RAM.

PaletteChanged

Occurs when the user switches to an application that uses a different palette.

PowerModeChanged

Occurs when the user suspends or resumes the system.

SessionEnded

Occurs when the user is logging off or shutting down the system.

SessionEnding

Occurs when the user is trying to log off or shut down the system.

SessionSwitch

Occurs when the currently logged-in user has changed.

TimeChanged

Occurs when the user changes the time on the system clock.

TimerElapsed

Occurs when a windows timer interval has expired.

UserPreferenceChanged

Occurs when a user preference has changed.

UserPreferenceChanging

Occurs when a user preference is changing.

Applies to

Product Versions
.NET 8 (package-provided), 9 (package-provided), 10 (package-provided)
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0 (package-provided)
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9, 10

See also