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
以下程式碼範例展示了一個非常簡單的Windows服務,處理 TimeChanged 和 UserPreferenceChanged 事件。 範例包含一個名為 SimpleService、 一個名為 、 的表單,以及一個安裝 HiddenForm程式。 表單提供系統事件所需的訊息迴圈。
Note
服務沒有訊息迴圈,除非被允許與桌面互動。 若訊息迴圈非由隱藏表單提供,如本例所示,服務必須以本地系統帳號執行,且需人工介入以啟用與桌面的互動。 也就是說,管理員必須手動勾選服務屬性對話框「登入」標籤中的「允許服務與桌面互動」勾選框。 此時會自動提供訊息迴圈。 此選項僅在服務以本地系統帳號執行時可用。 無法透過程式化啟用與桌面的互動。
此範例中的服務啟動一個執行緒,執行一個實例。HiddenForm 事件會以表格連接並處理。 這些事件必須在模具的載入事件中接入,以確保模具先完全載入;否則事件不會被提及。
Note
範例提供了所有必要的程式碼,包括通常由 Visual Studio 設計師產生的表單初始化程式碼。 如果你是在 Visual Studio 中開發服務,可以省略第二個部分類別,使用 Properties 視窗,將隱藏表單的高度和寬度設為零,邊框樣式設為 FormBorderStyle.None,視窗狀態設為 FormWindowState.Minimized。
舉個例子:
從指令列編譯程式碼。 你用來命名來源檔案的名稱並不重要。
從命令列使用 Installutil.exe(安裝工具) 工具安裝服務。 例如,
InstallUtil example.exe如果原始檔名是example.cs或example.vb。 安裝服務必須是管理員。請使用服務控制台啟動服務。
更改系統時間,或更改使用者偏好設定,例如滑鼠屬性。
查看事件檢視器Application類別中的訊息。
使用服務控制台停止服務。
透過使用
/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 方法。
注意事項
不要對啟動系統事件處理器的執行緒執行冗長的處理,因為這可能會阻礙其他應用程式的運作。
Note
有些系統事件在 Windows Vista 上可能不會被觸發。 務必確認你的應用程式在 Windows Vista 上正常運作。
方法
| 名稱 | Description |
|---|---|
| CreateTimer(Int32) |
建立一個與系統事件視窗相關的新視窗計時器。 |
| Equals(Object) |
判斷指定的物件是否等於目前的物件。 (繼承來源 Object) |
| GetHashCode() |
做為預設哈希函式。 (繼承來源 Object) |
| GetType() |
取得目前實例的 Type。 (繼承來源 Object) |
| InvokeOnEventsThread(Delegate) |
利用監聽系統事件的執行緒呼叫指定的代理。 |
| KillTimer(IntPtr) |
終止由指定 ID 指定的計時器。 |
| MemberwiseClone() |
建立目前 Object的淺層複本。 (繼承來源 Object) |
| ToString() |
傳回表示目前 物件的字串。 (繼承來源 Object) |
事件
| 名稱 | Description |
|---|---|
| DisplaySettingsChanged |
當使用者更改顯示設定時會發生。 |
| DisplaySettingsChanging |
當顯示設定改變時會發生。 |
| EventsThreadShutdown |
已淘汰.
發生在監聽系統事件的執行緒尚未終止之前。 |
| InstalledFontsChanged |
當使用者新增或移除系統中的字型時,會發生這種情況。 |
| LowMemory |
已淘汰.
已淘汰.
已淘汰.
當系統的可用記憶體快用盡時會發生。 |
| PaletteChanged |
當使用者切換到使用不同調色盤的應用程式時,會發生這種情況。 |
| PowerModeChanged |
當使用者暫停或恢復系統時,會發生這種情況。 |
| SessionEnded |
當使用者登出或關閉系統時會發生。 |
| SessionEnding |
當使用者嘗試登出或關閉系統時會發生。 |
| SessionSwitch |
當目前登入的使用者已經更改時會發生。 |
| TimeChanged |
當使用者更改系統時鐘的時間時,會發生這種情況。 |
| TimerElapsed |
當 Windows 計時器間隔結束時會發生。 |
| UserPreferenceChanged |
當使用者偏好改變時會發生。 |
| UserPreferenceChanging |
當使用者偏好改變時會發生。 |