Handling System Events in
VB.Net
Handling system events like display resolution changes or system
low memory has never been easier on VB6, while possible, you might have to resort
to subclassing or ocx. VB.Net allows you to catch system events easily by using
Win32's SystemEvents shared class.
To use that class you first must import Imports Microsoft.Win32 namespace,
the, create routines that will handle callback'ed system events.
Let's create an example that will 'trap' when user changes system time
1 - Create a blank project and import
Microsoft.Win32 namespace typing:
Imports Microsoft.Win32
2 - Add a button and within click
event add the following code:
Private Sub Button1_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
Button1.Click
AddHandler SystemEvents.TimeChanged, AddressOf
MyEH
AddHandler SystemEvents.DisplaySettingsChanged,
AddressOf MyEH2
RemoveHandler SystemEvents.DisplaySettingsChanged, AddressOf MyEH2
End Sub
3 - Add the following routines to
your form:
Public Sub MyEH(ByVal
sender As Object, ByVal e As EventArgs)
Me.Text = "Time has changed"
End Sub
Public Sub MyEH2(ByVal sender As Object,
ByVal e As EventArgs)
Me.Text = "Display has changed"
End Sub
4 - Add another button and within
click event add the following code:
Private Sub Button2_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
Button2.Click
RemoveHandler SystemEvents.TimeChanged,
AddressOf MyEH
RemoveHandler SystemEvents.DisplaySettingsChanged,
AddressOf MyEH2
End Sub
That's all, run your program then change system time or modify screen resolution,
you'll see Form's caption changing to 'Time has changed' or 'Display has changed'.
Don't forget to remove event handlers before closing your program by clicking
button2.
You can trap differents system events, some of them have a different delegate signature and lets you receive addition information about generated event so i suggest you to have a look at MSDN documentation for further investigations.
Available events are:
DisplaySettingsChanged
Occurs when the user changes the display settings.
EventsThreadShutdown
Occurs before the thread that listens for system events is terminated. Delegates
will be invoked on the events thread.
InstalledFontsChanged
Occurs when the user adds fonts to or removes fonts from the system.
LowMemory
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 shutdown the system.
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.
Enjoy system events trapping!