SystemEvents 類別
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
提供存取系統事件告知的功能。 此類別無法獲得繼承。
public ref class SystemEvents sealed
public sealed class SystemEvents
type SystemEvents = class
Public NotInheritable Class SystemEvents
- 繼承
-
SystemEvents
範例
本節包含兩個範例。 第一個範例示範如何在一般應用程式中使用系統事件,而第二個範例示範如何在 Windows 服務中使用系統事件。
範例 1
下列程式代碼範例會註冊某些系統事件的興趣,然後等候任何這些事件發生。 如果使用者變更顯示解析度,就會顯示輸出。
#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
範例 2
下列程式代碼範例示範處理 和 UserPreferenceChanged 事件的非常簡單的 Windows 服務TimeChanged。 此範例包含名為 SimpleService
的服務、名為 HiddenForm
的表單和安裝程式。 表單提供系統事件所需的訊息迴圈。
注意
除非允許服務與桌面互動,否則服務不會有訊息迴圈。 如果訊息迴圈不是由隱藏窗體提供,如此範例所示,服務必須在本機系統帳戶下執行,而且需要手動介入才能與桌面互動。 也就是說,系統管理員必須在 [服務屬性] 對話框的 [登入] 索引標籤上手動核取 [允許服務與桌面互動] 複選框。 在此情況下,系統會自動提供訊息迴圈。 只有在服務是在本機系統帳戶下執行時,才能使用此選項。 無法以程式設計方式啟用與桌面的互動。
此範例中的服務會啟動執行 實例的 HiddenForm
線程。 事件會以表單連結和處理。 事件必須在表單的載入事件中連結,以確保表單已完全載入;否則不會引發事件。
注意
此範例提供所有必要的程序代碼,包括 Visual Studio 設計工具通常產生的表單初始化程式代碼。 如果您要在 Visual Studio 中開發服務,可以省略第二個部分類別,並使用 [屬性 ] 視窗將隱藏表單的高度和寬度設定為零、框線樣式 FormBorderStyle.None設定為 ,並將視窗狀態設定為 FormWindowState.Minimized。
若要執行範例:
從命令行編譯程序代碼。 您用於來源檔案的名稱並不重要。
使用 Installutil.exe (Installer Tool) 公用程式,從命令行安裝服務。 例如,
InstallUtil example.exe
如果來源檔名為example.cs
或example.vb
。 您必須是系統管理員才能安裝服務。使用服務主控台啟動服務。
變更系統時間,或變更使用者喜好設定,例如滑鼠屬性。
在 事件檢視器 的 [應用程式] 類別中檢視訊息。
使用服務控制台停止服務。
使用
/u
選項,從命令行卸載服務。 例如: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 可讓您回應特定類型的系統事件。
引發系統事件時,會使用監視系統事件的線程來呼叫附加至事件的任何委派。 因此,您應該從事件處理程式線程安全進行任何呼叫。 如果您需要呼叫未公開為這個類別成員的系統事件,您可以使用 InvokeOnEventsThread 方法。
警告
請勿在引發系統事件處理程式的線程上執行耗時的處理,因為它可能會防止其他應用程式運作。
注意
某些系統事件可能不會在 Windows Vista 上引發。 請務必確認您的應用程式在 Windows Vista 上如預期般運作。
方法
CreateTimer(Int32) |
建立與系統事件視窗關聯的新視窗計時器。 |
Equals(Object) |
判斷指定的物件是否等於目前的物件。 (繼承來源 Object) |
GetHashCode() |
做為預設雜湊函式。 (繼承來源 Object) |
GetType() |
取得目前執行個體的 Type。 (繼承來源 Object) |
InvokeOnEventsThread(Delegate) |
利用接聽系統事件的執行緒叫用指定的委派。 |
KillTimer(IntPtr) |
終止指定 ID 代表的計時器。 |
MemberwiseClone() |
建立目前 Object 的淺層複製。 (繼承來源 Object) |
ToString() |
傳回代表目前物件的字串。 (繼承來源 Object) |
事件
DisplaySettingsChanged |
當使用者變更顯示設定時發生。 |
DisplaySettingsChanging |
當顯示設定變更時發生。 |
EventsThreadShutdown |
在聆聽系統事件的執行緒終止前發生。 |
InstalledFontsChanged |
當使用者將字型加入系統或從系統移除字型時發生。 |
LowMemory |
已淘汰.
已淘汰.
已淘汰.
當系統可用的 RAM 不足時發生。 |
PaletteChanged |
當使用者切換至使用不同調色盤的應用程式時發生。 |
PowerModeChanged |
當使用者暫停或繼續系統時發生。 |
SessionEnded |
當使用者正在登出或正在關閉系統時發生。 |
SessionEnding |
當使用者正在嘗試登出或關閉系統時發生。 |
SessionSwitch |
當目前登入的使用者變更時發生。 |
TimeChanged |
當使用者變更系統時鐘上的時間時發生。 |
TimerElapsed |
當視窗計時器間隔已經過期時發生。 |
UserPreferenceChanged |
當使用者喜好設定已變更時發生。 |
UserPreferenceChanging |
當使用者喜好設定正在變更時發生。 |