Export (0) Print
Expand All

SystemEvents Class

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

System.Object
  Microsoft.Win32.SystemEvents

Namespace:  Microsoft.Win32
Assembly:  System (in System.dll)

'Declaration
<PermissionSetAttribute(SecurityAction.LinkDemand, Name := "FullTrust")> _
<HostProtectionAttribute(SecurityAction.LinkDemand, MayLeakOnAbort := True)> _
Public NotInheritable Class SystemEvents

The SystemEvents type exposes the following members.

  NameDescription
Public methodStatic memberCreateTimerCreates a new window timer associated with the system events window.
Public methodEquals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Public methodGetHashCodeServes as the default hash function. (Inherited from Object.)
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodStatic memberInvokeOnEventsThreadInvokes the specified delegate using the thread that listens for system events.
Public methodStatic memberKillTimerTerminates the timer specified by the given id.
Public methodToStringReturns a string that represents the current object. (Inherited from Object.)
Top

  NameDescription
Public eventStatic memberDisplaySettingsChangedOccurs when the user changes the display settings.
Public eventStatic memberDisplaySettingsChangingOccurs when the display settings are changing.
Public eventStatic memberEventsThreadShutdownOccurs before the thread that listens for system events is terminated.
Public eventStatic memberInstalledFontsChangedOccurs when the user adds fonts to or removes fonts from the system.
Public eventStatic memberLowMemory Obsolete. Occurs when the system is running out of available RAM.
Public eventStatic memberPaletteChangedOccurs when the user switches to an application that uses a different palette.
Public eventStatic memberPowerModeChangedOccurs when the user suspends or resumes the system.
Public eventStatic memberSessionEndedOccurs when the user is logging off or shutting down the system.
Public eventStatic memberSessionEndingOccurs when the user is trying to log off or shut down the system.
Public eventStatic memberSessionSwitchOccurs when the currently logged-in user has changed.
Public eventStatic memberTimeChangedOccurs when the user changes the time on the system clock.
Public eventStatic memberTimerElapsedOccurs when a windows timer interval has expired.
Public eventStatic memberUserPreferenceChangedOccurs when a user preference has changed.
Public eventStatic memberUserPreferenceChangingOccurs when a user preference is changing.
Top

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 noteCaution

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

NoteNote

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

NoteNote

The HostProtectionAttribute attribute applied to this type or member has the following Resources property value: MayLeakOnAbort. The HostProtectionAttribute does not affect desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes.

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.

Imports System
Imports Microsoft.Win32
Imports System.Windows.Forms

Friend Class Form1
    Inherits System.Windows.Forms.Form


    Public Sub New()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Set the SystemEvents class to receive event notification  
        'when a user preference changes, the palette changes, or  
        'when display settings change. 
        AddHandler SystemEvents.UserPreferenceChanging, _
        AddressOf SystemEvents_UserPreferenceChanging

        AddHandler SystemEvents.PaletteChanged, _
        AddressOf SystemEvents_PaletteChanged

        AddHandler SystemEvents.DisplaySettingsChanged, _
        AddressOf SystemEvents_DisplaySettingsChanged

    End Sub 

    'Form overrides dispose to clean up the component list. 
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then 
            If (components IsNot Nothing) Then
                components.Dispose()
            End If 
        End If 
        MyBase.Dispose(disposing)
    End Sub 


    Private components As System.ComponentModel.IContainer

    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

        Me.SuspendLayout()

        
        'Form1 
        
        Me.ClientSize = New System.Drawing.Size(648, 398)
        Me.Name = "Form1" 
        Me.Text = "Form1" 
        Me.ResumeLayout(False)

    End Sub 


    ' This method is called when a user preference changes. 
    Private Sub SystemEvents_UserPreferenceChanging( _
    ByVal sender As Object, _
    ByVal e As UserPreferenceChangingEventArgs)

        MessageBox.Show("UserPreferenceChanging: " & _
        e.Category.ToString())
    End Sub 


    ' This method is called when the palette changes. 
    Private Sub SystemEvents_PaletteChanged( _
    ByVal sender As Object, _
    ByVal e As EventArgs)

        MessageBox.Show("PaletteChanged")

    End Sub 


    ' This method is called when the display settings change. 
    Private Sub SystemEvents_DisplaySettingsChanged( _
    ByVal sender As Object, _
    ByVal e As EventArgs)

        MessageBox.Show("The display settings changed.")

    End Sub 

End Class

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.

NoteNote

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.

NoteNote

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.

Imports System
Imports System.ServiceProcess
Imports System.Threading
Imports System.Windows.Forms
Imports System.Diagnostics
Imports Microsoft.Win32
Imports System.ComponentModel
Imports System.Configuration.Install

Namespace SimpleServiceVb
    Public Class SimpleService
        Inherits ServiceBase

        Shared Sub Main(ByVal args() As String) 
            ServiceBase.Run(New SimpleService())
        End Sub 

        Protected Overrides Sub OnStart(ByVal args() As String) 
            EventLog.WriteEntry("SimpleService", "Starting SimpleService")
            Dim t As New Thread(AddressOf RunMessagePump)
            t.Start()    
        End Sub 

        Sub RunMessagePump() 
            EventLog.WriteEntry("SimpleService.MessagePump", _
                "Starting SimpleService Message Pump")
            Application.Run(New HiddenForm())
        End Sub 

        Protected Overrides Sub OnStop() 
            Application.Exit()
        End Sub 
    End Class  

    Partial Class HiddenForm
        Inherits Form

        Public Sub New() 
            InitializeComponent()
        End Sub 

        Private Sub HiddenForm_Load(ByVal sender As Object, ByVal e As EventArgs) 
            AddHandler SystemEvents.TimeChanged, AddressOf SystemEvents_TimeChanged
            AddHandler SystemEvents.UserPreferenceChanged, AddressOf SystemEvents_UPCChanged
        End Sub  

        Private Sub HiddenForm_FormClosing(ByVal sender As Object, ByVal e As FormClosingEventArgs) 
            RemoveHandler SystemEvents.TimeChanged, New EventHandler(AddressOf SystemEvents_TimeChanged)
            RemoveHandler SystemEvents.UserPreferenceChanged, _
                New UserPreferenceChangedEventHandler(AddressOf SystemEvents_UPCChanged)
        End Sub  

        Private Sub SystemEvents_TimeChanged(ByVal sender As Object, ByVal e As EventArgs) 
            EventLog.WriteEntry("SimpleService.TimeChanged", _
                "Time changed; it is now " & DateTime.Now.ToLongTimeString())
        End Sub  

        Private Sub SystemEvents_UPCChanged(ByVal sender As Object, ByVal e As UserPreferenceChangedEventArgs) 
            EventLog.WriteEntry("SimpleService.UserPreferenceChanged", e.Category.ToString())
        End Sub  
    End Class 

    Partial Class HiddenForm

        Private components As System.ComponentModel.IContainer = Nothing 

        Protected Overrides Sub Dispose(ByVal disposing As Boolean) 
            If disposing AndAlso Not (components Is Nothing) Then
                components.Dispose()
            End If 
            MyBase.Dispose(disposing)
        End Sub 

        Private Sub InitializeComponent() 
            Me.SuspendLayout()
            Me.AutoScaleDimensions = New System.Drawing.SizeF(6F, 13F)
            Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
            Me.ClientSize = New System.Drawing.Size(0, 0)
            Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None
            Me.Name = "HiddenForm" 
            Me.Text = "HiddenForm" 
            Me.WindowState = System.Windows.Forms.FormWindowState.Minimized
            AddHandler Me.Load, AddressOf Me.HiddenForm_Load
            AddHandler Me.FormClosing, AddressOf Me.HiddenForm_FormClosing
            Me.ResumeLayout(False)
        End Sub  
    End Class 

    <RunInstaller(True)> _
    Public Class SimpleInstaller
        Inherits Installer

        Private serviceInstaller As ServiceInstaller
        Private processInstaller As ServiceProcessInstaller

        Public Sub New() 
            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)
        End Sub 
    End Class  
End Namespace

.NET Framework

Supported in: 4.5.2, 4.5.1, 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Show:
© 2014 Microsoft