SystemEvents.PowerModeChanged Event
Assembly: System (in system.dll)
Windows 98, Windows Server 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
The Microsoft .NET Framework 3.0 is supported on Windows Vista, Microsoft Windows XP SP2, and Windows Server 2003 SP1.In order to prevent a memory leak, as noted, you must unregister from this event. To detach from the event in C++, keep a reference to the handler-delegate until disposal time, something like this:
ref class Test
{
// Here's the reference we'll keep until we've unregistered
Microsoft::Win32::PowerModeChangedEventHandler^ m_powerModeChangedDelegate;
public:
Test()
{// Create the delegate (for pedants, note that we don't use an initializer
// list since we are making explicit use of the "this" pointer).
m_powerModeChangedDelegate =
gcnew Microsoft::Win32::PowerModeChangedEventHandler(
this, &Test::PowerModeChangedHandler );
// Register for host power mode changes
Microsoft::Win32::SystemEvents::PowerModeChanged += m_powerModeChangedDelegate;
}
~Test() // Destructor is the "Dispose" method in C++/CLI
{
// Unregister for host power mode changes
Microsoft::Win32::SystemEvents::PowerModeChanged -= m_powerModeChangedDelegate;
}
void PowerModeChangedHandler(
Object^ sender, Microsoft::Win32::PowerModeChangedEventArgs^ e )
{
// ... handle event here ...
}
};
As cautioned above, if attaching to this event to an instance method, as opposed to a static (Shared in Visual Basic) method, you must detach from the event or the attached object will be around in memory until the process exits. This is typically done in the dispose method of the object.
The following example shows a form that attaches to the SystemEvents.PowerModeChanged event and then detaches from the event in its Dispose(bool) implementation.
[C#]
using System;
using System.Windows.Forms;
using Microsoft.Win32;
namespace Samples
{
public class MyForm : Form
{
public MyForm()
{
SystemEvents.PowerModeChanged += OnPowerModeChanged;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
SystemEvents.PowerModeChanged -= OnPowerModeChanged;
}
base.Dispose(disposing);
}
private void OnPowerModeChanged(object sender, PowerModeChangedEventArgs e)
{
MessageBox.Show("PowerModeChanged");
}
}
}
- 8/25/2007
- David M. Kean
- 8/25/2007
- David M. Kean
Caution: