SystemEvents SystemEvents SystemEvents SystemEvents Class

Definición

Proporciona acceso a notificaciones de eventos del sistema.Provides access to system event notifications. Esta clase no puede heredarse.This class cannot be inherited.

public ref class SystemEvents sealed
public sealed class SystemEvents
type SystemEvents = class
Public NotInheritable Class SystemEvents
Herencia
SystemEventsSystemEventsSystemEventsSystemEvents

Ejemplos

Esta sección contiene dos ejemplos.This section contains two examples. El primer ejemplo muestra cómo utilizar los eventos del sistema en una aplicación normal, y el segundo ejemplo muestra cómo usar los eventos del sistema en un servicio de Windows.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.

Ejemplo 1Example 1

El ejemplo de código siguiente registra el interés en algunos eventos del sistema y, a continuación, espera a que cualquiera de esos eventos se producen.The following code example registers interest in some system events and then waits for any of those events to occur. Se produce el resultado que se muestra si el usuario cambia la resolución de pantalla.The output shown occurs if the user changes the display resolution.

#using <System.dll>

using namespace System;
using namespace Microsoft::Win32;

// This method is called when a user preference changes.
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.
void SystemEvents_PaletteChanged(Object^ sender, EventArgs^ e)
{
    Console::WriteLine("The palette changed.");
}

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

int main()
{
    // Set the SystemEvents class to receive event notification
    // when a user preference changes, the palette changes, or
    // when display settings change.
    SystemEvents::UserPreferenceChanging += gcnew
        UserPreferenceChangingEventHandler(
        SystemEvents_UserPreferenceChanging);
    SystemEvents::PaletteChanged += gcnew
        EventHandler(SystemEvents_PaletteChanged);
    SystemEvents::DisplaySettingsChanged += gcnew
        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 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
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
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

Ejemplo 2Example 2

En el ejemplo de código siguiente se muestra un servicio de Windows muy simple que controla la TimeChanged y UserPreferenceChanged eventos.The following code example demonstrates a very simple Windows service that handles the TimeChanged and UserPreferenceChanged events. El ejemplo incluye un servicio denominado SimpleService, un formulario denominado HiddenFormy un instalador.The example includes a service named SimpleService, a form named HiddenForm, and an installer. El formulario proporciona el bucle de mensajes que requiere los eventos del sistema.The form provides the message loop that is required by system events.

Nota

Los servicios no tiene bucles de mensajes, a menos que pueden interactuar con el escritorio.Services do not have message loops, unless they are allowed to interact with the desktop. Si el bucle de mensajes no se proporciona un formulario oculto, como se muestra en este ejemplo, el servicio debe ejecutarse con la cuenta sistema local y se requiere la intervención manual para habilitar la interacción con el escritorio.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. Es decir, el administrador debe comprobar manualmente la permitir que el servicio interactúe con el escritorio casilla de verificación en la iniciar sesión ficha del cuadro de diálogo de propiedades de servicio.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. En ese caso, se proporciona automáticamente un bucle de mensajes.In that case, a message loop is automatically provided. Esta opción está disponible solo cuando el servicio se ejecuta bajo la cuenta sistema local.This option is available only when the service is run under the local system account. No se puede habilitar mediante programación la interacción con el escritorio.Interaction with the desktop cannot be enabled programmatically.

El servicio en este ejemplo inicia un subproceso que ejecuta una instancia de HiddenForm.The service in this example starts a thread that runs an instance of HiddenForm. Los eventos se enlazan y se controlan en el formulario.The events are hooked up and handled in the form. Los eventos se deben enlazar en el evento de carga del formulario, para asegurarse de que el formulario está completamente cargado en primer lugar; en caso contrario, los eventos no se generará.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.

Nota

En el ejemplo se proporciona todo el código necesario, incluido el código de inicialización del formulario normalmente generado por los diseñadores de Visual Studio.The example provides all the necessary code, including the form initialization code typically generated by Visual Studio designers. Si está desarrollando su servicio en Visual Studio, puede omitir la segunda clase parcial y usar el propiedades ventana para establecer el alto y ancho del formulario oculto en cero, el estilo de borde FormBorderStyle.Noney el estado de la ventana FormWindowState.Minimized.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.

Para ejecutar el ejemplo:To run the example:

  1. Compile el código desde la línea de comandos.Compile the code from the command line. El nombre que usó para el archivo de origen no es importante.The name that you use for the source file is not important.

  2. Instalar el servicio desde la línea de comandos mediante la Installutil.exe (herramienta Installer) utilidad.Install the service from the command line using the Installutil.exe (Installer Tool) utility. Por ejemplo, InstallUtil example.exe si el nombre de archivo de origen es example.cs o example.vb.For example, InstallUtil example.exe if the source file name is example.cs or example.vb. Debe ser un administrador para instalar el servicio.You must be an administrator to install the service.

  3. Use la consola Servicios para iniciar el servicio.Use the Services console to start the service.

  4. Cambiar la hora del sistema, o cambiar las preferencias del usuario, como las propiedades de mouse.Change the system time, or change user preferences, such as mouse properties.

  5. Ver los mensajes en el aplicación categoría del Visor de eventos.View the messages in the Application category of Event Viewer.

  6. Use la consola Servicios para detener el servicio.Use the Services console to stop the service.

  7. Desinstalar el servicio de la línea de comandos mediante el /u opción.Uninstall the service from the command line by using the /u option. Por ejemplo: InstallUtil /u example.exe.For example, InstallUtil /u example.exe.

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

Comentarios

La SystemEvents clase proporciona la capacidad para responder a determinados tipos de eventos del sistema.The SystemEvents class provides the ability to respond to specific types of system events.

Cuando se genera un evento del sistema, todos los delegados asociados al evento se denominan mediante el subproceso que supervisa los eventos del sistema.When a system event is raised, any delegates attached to the event are called using the thread that monitors for system events. Por lo tanto, debe realizar las llamadas desde el evento controladores seguros para subprocesos.Therefore, you should make any calls from your event handlers thread-safe. Si necesita llamar a un evento del sistema que no se expone como un miembro de esta clase, puede usar el InvokeOnEventsThread método.If you need to call a system event that is not exposed as a member of this class, you can use the InvokeOnEventsThread method.

Precaución

No realizan ningún procesamiento mucho tiempo en el subproceso que genera un controlador de eventos del sistema porque podría impedir que otras aplicaciones funcionen.Do not perform time-consuming processing on the thread that raises a system event handler because it might prevent other applications from functioning.

Nota

Algunos eventos del sistema no es posible que se producen en Windows VistaWindows Vista.Some system events might not be raised on Windows VistaWindows Vista. Asegúrese de comprobar que la aplicación funciona según lo previsto en Windows VistaWindows Vista.Be sure to verify that your application works as expected on Windows VistaWindows Vista.

Métodos

CreateTimer(Int32) CreateTimer(Int32) CreateTimer(Int32) CreateTimer(Int32)

Crea un nuevo temporizador de ventana asociado a la ventana de eventos del sistema.Creates a new window timer associated with the system events window.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Determina si el objeto especificado es igual al objeto actual.Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Sirve como la función hash predeterminada.Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

Obtiene el Type de la instancia actual.Gets the Type of the current instance.

(Inherited from Object)
InvokeOnEventsThread(Delegate) InvokeOnEventsThread(Delegate) InvokeOnEventsThread(Delegate) InvokeOnEventsThread(Delegate)

Invoca al delegado especificado mediante el subproceso que escucha eventos del sistema. Invokes the specified delegate using the thread that listens for system events.

KillTimer(IntPtr) KillTimer(IntPtr) KillTimer(IntPtr) KillTimer(IntPtr)

Termina el temporizador especificado por el identificador dado.Terminates the timer specified by the given id.

MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Crea una copia superficial del objeto Object actual.Creates a shallow copy of the current Object.

(Inherited from Object)
ToString() ToString() ToString() ToString()

Devuelve una cadena que representa el objeto actual.Returns a string that represents the current object.

(Inherited from Object)

Eventos

DisplaySettingsChanged DisplaySettingsChanged DisplaySettingsChanged DisplaySettingsChanged

Se produce cuando el usuario cambia la configuración de pantalla.Occurs when the user changes the display settings.

DisplaySettingsChanging DisplaySettingsChanging DisplaySettingsChanging DisplaySettingsChanging

Se produce cuando la configuración de pantalla está cambiando.Occurs when the display settings are changing.

EventsThreadShutdown EventsThreadShutdown EventsThreadShutdown EventsThreadShutdown

Se produce antes de que finalice el subproceso que escucha los eventos del sistema.Occurs before the thread that listens for system events is terminated.

InstalledFontsChanged InstalledFontsChanged InstalledFontsChanged InstalledFontsChanged

Se produce cuando el usuario agrega o quita fuentes del sistema.Occurs when the user adds fonts to or removes fonts from the system.

LowMemory LowMemory LowMemory LowMemory

Se produce cuando el sistema se queda sin RAM disponible.Occurs when the system is running out of available RAM.

PaletteChanged PaletteChanged PaletteChanged PaletteChanged

Se produce cuando el usuario cambia a una aplicación que utiliza una paleta diferente.Occurs when the user switches to an application that uses a different palette.

PowerModeChanged PowerModeChanged PowerModeChanged PowerModeChanged

Se produce cuando el usuario suspende o reanuda el sistema.Occurs when the user suspends or resumes the system.

SessionEnded SessionEnded SessionEnded SessionEnded

Se produce cuando el usuario cierra una sesión o apaga el sistema.Occurs when the user is logging off or shutting down the system.

SessionEnding SessionEnding SessionEnding SessionEnding

Se produce cuando el usuario intenta cerrar una sesión o apagar el sistema.Occurs when the user is trying to log off or shut down the system.

SessionSwitch SessionSwitch SessionSwitch SessionSwitch

Se produce cuando el usuario registrado actualmente ha cambiado.Occurs when the currently logged-in user has changed.

TimeChanged TimeChanged TimeChanged TimeChanged

Se produce cuando el usuario cambia la hora en el reloj del sistema.Occurs when the user changes the time on the system clock.

TimerElapsed TimerElapsed TimerElapsed TimerElapsed

Se produce cuando ha expirado el intervalo del temporizador de Windows.Occurs when a windows timer interval has expired.

UserPreferenceChanged UserPreferenceChanged UserPreferenceChanged UserPreferenceChanged

Se produce cuando han cambiado las preferencias de un usuario.Occurs when a user preference has changed.

UserPreferenceChanging UserPreferenceChanging UserPreferenceChanging UserPreferenceChanging

Se produce cuando se van a cambiar las preferencias de un usuario.Occurs when a user preference is changing.

Seguridad

NamedPermissionSet
Para obtener acceso completo a los recursos del sistema.for full access to system resources. Valores de petición: LinkDemand.Demand values: LinkDemand. Estado asociado:Associated state:

Se aplica a

Consulte también: