Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Try this:</p> <p>[EDIT] This is a modified version from the link posted above.</p> <p>NOTE: If the user clicks the red X to close the console window, you have a VERY limited time to respond before your app is killed! If you run the following program, look at how long the message box is displayed before it dies.</p> <pre><code>using System; using System.Runtime.InteropServices; using System.Threading; using System.Windows.Forms; namespace Demo { class Program { static void Main(string[] args) { SetConsoleCtrlHandler(ConsoleCtrlCheck, true); Console.WriteLine("CTRL+C,CTRL+BREAK or suppress the application to exit"); while (!isclosing) { Thread.Sleep(1000); } } private static bool ConsoleCtrlCheck(CtrlTypes ctrlType) { // Put your own handling here: switch (ctrlType) { case CtrlTypes.CTRL_C_EVENT: isclosing = true; Console.WriteLine("CTRL+C received!"); break; case CtrlTypes.CTRL_BREAK_EVENT: isclosing = true; Console.WriteLine("CTRL+BREAK received!"); break; case CtrlTypes.CTRL_CLOSE_EVENT: isclosing = true; Console.WriteLine("Program being closed!"); MessageBox.Show("AHA!"); break; case CtrlTypes.CTRL_LOGOFF_EVENT: case CtrlTypes.CTRL_SHUTDOWN_EVENT: isclosing = true; Console.WriteLine("User is logging off!"); break; } return true; } #region unmanaged // Declare the SetConsoleCtrlHandler function as external and receiving a delegate. [DllImport("Kernel32")] public static extern bool SetConsoleCtrlHandler(HandlerRoutine Handler, bool Add); // A delegate type to be used as the handler routine for SetConsoleCtrlHandler. public delegate bool HandlerRoutine(CtrlTypes CtrlType); // An enumerated type for the control messages sent to the handler routine. public enum CtrlTypes { CTRL_C_EVENT = 0, CTRL_BREAK_EVENT, CTRL_CLOSE_EVENT, CTRL_LOGOFF_EVENT = 5, CTRL_SHUTDOWN_EVENT } #endregion private static bool isclosing; } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload