SystemEvents Класс
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Предоставляет доступ к уведомлениям системных событий. Этот класс не наследуется.
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.
Методы
| Имя | Описание |
|---|---|
| CreateTimer(Int32) |
Создает новый таймер окна, связанный с окном системных событий. |
| Equals(Object) |
Определяет, равен ли указанный объект текущему объекту. (Унаследовано от Object) |
| GetHashCode() |
Служит хэш-функцией по умолчанию. (Унаследовано от Object) |
| GetType() |
Возвращает Type текущего экземпляра. (Унаследовано от Object) |
| InvokeOnEventsThread(Delegate) |
Вызывает указанный делегат с помощью потока, прослушивающего системные события. |
| KillTimer(IntPtr) |
Завершает таймер, указанный заданным идентификатором. |
| MemberwiseClone() |
Создает неглубокую копию текущей Object. (Унаследовано от Object) |
| ToString() |
Возвращает строку, представляющую текущий объект. (Унаследовано от Object) |
События
| Имя | Описание |
|---|---|
| DisplaySettingsChanged |
Происходит, когда пользователь изменяет параметры отображения. |
| DisplaySettingsChanging |
Происходит при изменении параметров отображения. |
| EventsThreadShutdown |
Происходит перед завершением потока, прослушивающего системные события. |
| InstalledFontsChanged |
Происходит, когда пользователь добавляет шрифты в систему или удаляет их из системы. |
| LowMemory |
Устаревшие..
Происходит, когда система выходит из доступной оперативной памяти. |
| PaletteChanged |
Происходит, когда пользователь переключается на приложение, использующее другую палитру. |
| PowerModeChanged |
Происходит, когда пользователь приостанавливает или возобновляет работу системы. |
| SessionEnded |
Происходит, когда пользователь отключает или завершает работу системы. |
| SessionEnding |
Возникает, когда пользователь пытается выйти или завершить работу системы. |
| SessionSwitch |
Происходит при изменении текущего пользователя, вошедшего в систему. |
| TimeChanged |
Происходит, когда пользователь изменяет время в системных часах. |
| TimerElapsed |
Происходит при истечении интервала таймера windows. |
| UserPreferenceChanged |
Происходит при изменении предпочтения пользователя. |
| UserPreferenceChanging |
Происходит при изменении предпочтения пользователя. |