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
窗体和安装程序的服务。 该窗体提供系统事件所需的消息循环。
备注
除非允许服务与桌面交互,否则服务没有消息循环。 如果消息循环不是由隐藏窗体提供的,如本示例中所示,必须在本地系统帐户下运行服务,并且需要手动干预才能启用与桌面的交互。 也就是说,管理员必须手动选中 “允许服务与 服务属性”对话框的 “登录 ”选项卡上的桌面复选框进行交互。 在这种情况下,会自动提供消息循环。 仅当服务在本地系统帐户下运行时,此选项才可用。 无法以编程方式启用与桌面的交互。
此示例中的服务启动运行实例的 HiddenForm
线程。 事件以窗体进行挂钩和处理。 必须在窗体的加载事件中挂接事件,以确保首先完全加载窗体;否则不会引发事件。
备注
该示例提供所有必要的代码,包括通常由Visual Studio设计器生成的表单初始化代码。 如果要在 Visual Studio 中开发服务,则可以省略第二个分部类,并使用 “属性” 窗口将隐藏窗体的高度和宽度设置为零、边框样式设置为FormBorderStyle.None和窗口状态。FormWindowState.Minimized
运行示例:
从命令行编译代码。 用于源文件的名称并不重要。
使用 Installutil.exe (安装程序工具) 实用工具从命令行安装服务。 例如,
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 |
当用户首选项更改时发生。 |