| To clarify some more, I want to catch CTRL+C for a program which is
| running on command prompt (DOS box).
|
| Samik R. wrote:
| > Hello,
| >
| > Is there a way to catch CTRL+C key pressed by an user? Can someone point
| > me to an example code block?
| >
| > Thanks.
| > -Samik
You nned to register your own Console control handler by calling Win32 API
SetConsoleCtrlHandler using PInvoke.
Consider following snippet as a sample.
enum CtrlType {
CTRL_C_EVENT = 0,
CTRL_BREAK_EVENT = 1,
CTRL_CLOSE_EVENT = 2,
CTRL_LOGOFF_EVENT = 5,
CTRL_SHUTDOWN_EVENT = 6
}
private delegate bool EventHandler(CtrlType sig);
private static bool Handler(CtrlType sig)
{
bool handled = false;
switch (sig)
{
case CtrlType.CTRL_C_EVENT:
case CtrlType.CTRL_LOGOFF_EVENT:
case CtrlType.CTRL_SHUTDOWN_EVENT:
case CtrlType.CTRL_CLOSE_EVENT:
{
.. do whatever you like when one of the above occur (here for
all
events), but keep in mind that the system will kill the process
when you fail to return within 30 seconds.
}
// return true when handled, this signals the system to remove
the process
handled = true;
break;
default:
// return false when not handled
return handled;
}
return handled;
}
static EventHandler _handler;
[DllImport("Kernel32")]
private static extern bool SetConsoleCtrlHandler (EventHandler handler,
bool add);
static void Main()
{
// install the handler
_handler += new EventHandler(Handler);
SetConsoleCtrlHandler(_handler, true);
// ...