SystemEvents 類別

定義

提供存取系統事件告知的功能。Provides access to system event notifications. 此類別無法獲得繼承。This class cannot be inherited.

public ref class SystemEvents sealed
public sealed class SystemEvents
type SystemEvents = class
Public NotInheritable Class SystemEvents
繼承
SystemEvents

範例

本節包含兩個範例。This section contains two examples. 第一個範例示範如何在一般應用程式中使用系統事件,而第二個範例示範如何在 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.

範例 1Example 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.

#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 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

範例 2Example 2

下列程式碼範例示範一個非常簡單的 Windows 服務,可處理 TimeChangedUserPreferenceChanged 事件。The following code example demonstrates a very simple Windows service that handles the TimeChanged and UserPreferenceChanged events. 此範例包含名為的服務 SimpleService 、名為的表單 HiddenForm ,以及安裝程式。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.

注意

除非允許服務與桌面互動,否則服務沒有訊息迴圈。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.

此範例中的服務會啟動執行實例的執行緒 HiddenFormThe service in this example starts a thread that runs an instance of HiddenForm. 這些事件會以表單連結和處理。The events are hooked up and handled in the form. 事件必須在表單的 load 事件中連接,以確保表單會先完全載入;否則將不會引發事件。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.

注意

此範例會提供所有必要的程式碼,包括通常由 Visual Studio 設計師產生的表單初始化程式碼。The example provides all the necessary code, including the form initialization code typically generated by Visual Studio designers. 如果您要在 Visual Studio 中開發服務,可以省略第二個部分類別,並使用 [ 屬性 ] 視窗,將隱藏表單的高度和寬度設定為零、將框線樣式設定為 FormBorderStyle.None ,以及將視窗狀態設定為 FormWindowState.MinimizedIf 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. 使用 Installutil.exe (安裝程式工具) 公用程式,從命令列安裝服務。Install the service from the command line using the Installutil.exe (Installer Tool) utility. 例如, InstallUtil example.exe 如果原始程式檔名稱是或,則為 example.cs example.vbFor 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. 使用選項,從命令列卸載服務 /uUninstall the service from the command line by using the /u option. 例如,InstallUtil /u example.exeFor 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.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

備註

SystemEvents類別提供回應特定類型系統事件的能力。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. 如果您需要呼叫的系統事件不會公開為這個類別的成員,您可以使用 InvokeOnEventsThread 方法。If you need to call a system event that is not exposed as a member of this class, you can use the InvokeOnEventsThread method.

警告

請勿在引發系統事件處理常式的執行緒上執行耗時的處理,因為它可能會導致其他應用程式無法運作。Do not perform time-consuming processing on the thread that raises a system event handler because it might prevent other applications from functioning.

注意

某些系統事件可能不會引發 Windows VistaWindows VistaSome system events might not be raised on Windows VistaWindows Vista. 請務必確認您的應用程式如預期般運作 Windows VistaWindows VistaBe sure to verify that your application works as expected on Windows VistaWindows Vista.

方法

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.

(繼承來源 Object)
GetHashCode()

做為預設雜湊函式。Serves as the default hash function.

(繼承來源 Object)
GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(繼承來源 Object)
InvokeOnEventsThread(Delegate)

利用接聽系統事件的執行緒叫用指定的委派。Invokes the specified delegate using the thread that listens for system events.

KillTimer(IntPtr)

終止指定 ID 代表的計時器。Terminates the timer specified by the given id.

MemberwiseClone()

建立目前 Object 的淺層複製。Creates a shallow copy of the current Object.

(繼承來源 Object)
ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(繼承來源 Object)

事件

DisplaySettingsChanged

當使用者變更顯示設定時發生。Occurs when the user changes the display settings.

DisplaySettingsChanging

當顯示設定變更時發生。Occurs when the display settings are changing.

EventsThreadShutdown

在聆聽系統事件的執行緒終止前發生。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
已過時。
已過時。
已過時。

當系統可用的 RAM 不足時發生。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.

適用於

另請參閱