C # Register Control handler (SetConsoleCtrlHandler) Function Example console shutdown event overwrite

Source: Internet
Author: User

Adds or removes an application-defined handlerroutine function from the calling process's handler list.

Win32 API
Function:
Adds or removes an application-defined handlerroutine function from the calling process's handler list.
Function Prototypes:
BOOL SetConsoleCtrlHandler (
Phandler_routine Handlerroutine,//callback function
BOOL Add//Indicates whether to add or remove
);
return value: type bool
Parameters
Parameter handlerroutine: An application-defined pointer handlerroutine feature to be added or removed. This parameter can be null.
Parameter add: If this parameter is true, the handler is added, and if it is false, the handler will be deleted.
return value:
If the function fails, the return value is 0. Otherwise, a value other than 0 is returned. To get more error messages, call the GetLastError function.
Plainly, it is a system call.
The first argument is a function pointer, which is the function above. The second parameter is the flag, if True then install the hook, if False then remove the hook.

Using the Windows API to intercept the console's manual shutdown event message, the following is a complete example:

Using system;using system.collections.generic;using system.runtime.interopservices;using System.Text;using system.threading;/************************************************************************//* CSharp Console Shutdown Event Overwrite * Powered by:testcs_dn * BLOG:HTTP://BLOG.CSDN.NET/TESTCS_DN *//**************************************************** /namespace CSharp Console Shutdown Event Overwrite {//<summary>///console Shutdown Event overwrite//This shows the Windows API setconsole    The application of the Ctrlhandler function, while showing the use of the thread timer;///AUTHOR:TESTCS_DN//date:2015-01-03//</summary> class program  {//<summary>/////Timer callback function, where to handle the judgment of whether the timed time arrives and what to do;///</summary>//<param  Name= "obj" ></param> public static void Workovertimetimercallback (Object obj) {DateTime            DT = DateTime.Now; if (dt. Hour = = && dt.            Minute > 0) {Console.WriteLine ("OK"); }}//Timer variable PublIC static System.Threading.Timer Workovertimetimer = null;        Defines the handler delegate delegate bool Consolectrldelegate (int dwctrltype);        const int ctrl_close_event = 2; Import Setctrlhandlerhandler API [DllImport ("Kernel32.dll")] private static extern bool SetConsoleCtrlHandler (C        Onsolectrldelegate Handlerroutine, bool Add); static void Main (string[] args) {consolectrldelegate newdelegate = new Consolectrldelegate (Handlerrouti            NE); if (SetConsoleCtrlHandler (NewDelegate, True)) {//Initialize timer Workovertimetimer = new                System.Threading.Timer (New TimerCallback (workovertimetimercallback), NULL, 1000, 10000); To perform your own task here, I gave an example of "...", in order to show the long task, I used a dead loop;//Avoid too much output, use sleep;//Note: Sleep time is not too long, otherwise it may affect cons Ole.                    ReadKey (), resulting in the inability to receive user input; while (true) {Console.WriteLine ("...");     Thread.Sleep (100);           }} else {Console.WriteLine ("Sorry, API injection failed, press any key to exit!")                ");            Console.readkey ();  }}////<summary>///handler routines, where you write handler code for the specified event////</summary>//<param Name= "Ctrltype" ></param>///<returns></returns> static bool Handlerroutine (int ctrlty                    PE) {switch (ctrltype) {case ctrl_close_event://user is shutting down console                    Console.WriteLine (); Console.WriteLine ("The task is not completed, confirm that you want to exit?")                    (y/n) ");                    Consolekeyinfo ki = Console.readkey (); Return KI.                Key = = Consolekey.y;            Default:return true; }        }    }}
Reference: http://msdn.microsoft.com/en-us/library/ms686016 (v=vs.85). aspx

C # Register Control handler (SetConsoleCtrlHandler) Function Example console shutdown event overwrite

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.