I need to sign off when I go to work at the company, but I will forget it once every three minutes. What should we do, so we thought we could not capture Windows Shutdown events and make Program Ask it to remind me when it is shut down.
Very lucky and easy to find Microsoft. the systemevents class under the Win32 namespace, which has a static event sessionending that occurs when the system is logged out or shut down. This event is only valid in winform programs, but not in console programs, do not trigger events; another point is that we must remove the added events when the program is launched, otherwise it will easily cause memory overflow.
KeyCodeAs follows:
Using system;
Using system. Collections. Generic;
Using system. Windows. forms;
Using Microsoft. Win32;
Namespace Shutdown
{
Static class Program
{
////
/// Main entry point of the application.
///
[Stathread]
Static void main ()
{
Application. enablevisualstyles ();
Application. setcompatibletextrenderingdefault (false );
Formshutdown = new formshutdown ();
Systemevents. sessionending + = new sessionendingeventhandler (formshutdown. systemevents_sessionending );
Application. Run (formshutdown );
}
}
} Form code:
Using system;
Using system. Collections. Generic;
Using system. componentmodel;
Using system. Data;
Using system. drawing;
Using system. text;
Using system. Windows. forms;
Using Microsoft. Win32;
Namespace Shutdown
{
Public partial class formshutdown: Form
{
Const string message_txt = "Have you signed back? ";
Const string message_title = "prompt ";
Public formshutdown ()
{
Initializecomponent ();
}
Internal void systemevents_sessionending (Object sender, sessionendingeventargs E)
{
Dialogresult result = MessageBox. Show (message_txt, message_title, messageboxbuttons. yesno );
E. Cancel = (result = dialogresult. No );
}
Private void formshutdown_load (Object sender, eventargs E)
{
This. Location = new point (screen. primaryscreen. workingarea. Width-200, 0 );
}
Protected override void onclosed (eventargs E)
{
Systemevents. sessionending-= new sessionendingeventhandler (this. systemevents_sessionending );
Base. onclosed (E );
}
}
}
This program passed the test in Windows2003 using C #2.0. When using the systemevents. sessionending event, remember to remove the event when the program exits.
However, there are two regrets:
1. This method cannot capture sleep events.
2. This program occupies too much memory, and only such a small function actually occupies 12 Mb of memory, which is caused by. NET Framework. It is incredible.
Do you have any good ideas to overcome these two shortcomings?