2009-02-10 9 views
3

Je sais que l'interface graphique a Remplacer la console Fermer

private void Form1_Closing(object sender, System.ComponentModel.EventArgs e) 
{ 
    //do stuff 
}
Mais comment puis-je faire la même chose dans une application de la console? .

C#/NET3.5

Répondre

5

Voilà comment:

// 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 
} 

private static bool ConsoleCtrlCheck(CtrlTypes ctrlType) 
{ 
    // Put your own handler here 
    return true; 
} 

... 

SetConsoleCtrlHandler(new HandlerRoutine(ConsoleCtrlCheck), true); 
+0

Où puis-je en savoir plus à ce sujet? Je ne comprends pas complètement comment l'utiliser. – Dacto

+0

En savoir plus sur P/Invoke (ou PInvoke) sur MSDN. Docs sur SetConsoleCtrlHandler() sont là aussi. –

+0

Ok, donc j'ai un peu plus d'une compréhension, mais je ne sais toujours pas comment bloquer le CTRL_CLOSE_EVENT, Ive a essayé de retourner faux/vrai si elle attrape cet événement, mais sans succès. – Dacto

Questions connexes