Windows控制台应用程序中处理Ctrl+C等

Just a small code snippet: Let's say you write a console application in native C++ for Windows. Closing the console by pressing Ctrl+C,Ctrl+Break or clicking on close window button [X] kills the process. Is there any way to handle such event and close the program gracefully? Ther answer is calling SetConsoleCtrlHandler() WinAPI function and implementing your own Handler Routine callback function. The template looks like this:

//Handler function will be called on separate thread!

staticBOOL WINAPI console_ctrl_handler(DWORD dwCtrlType)

{

  switch (dwCtrlType)

  {

  case CTRL_C_EVENT: // Ctrl+C

    break;

  case CTRL_BREAK_EVENT: // Ctrl+Break

    break;

  case CTRL_CLOSE_EVENT: // Closing the consolewindow

    break;

  case CTRL_LOGOFF_EVENT: // User logs off. Passed only to services!

    break;

  case CTRL_SHUTDOWN_EVENT: // System is shutting down. Passed only to services!

    break;

  }

 

  // Return TRUE if handled this message,further handler functions won't be called.

  // Return FALSE to pass this message to further handlers until default handler calls ExitProcess().

  return FALSE;

}

 

int main(int argc, char **argv)

{

  SetConsoleCtrlHandler(console_ctrl_handler,TRUE);

  ...

}

If your program performs some loop and you want the user to be able to break it by closing the console or pressing Ctrl+C, you can solveit this way:

staticvolatile bool g_exit = false;

 

staticBOOL WINAPI console_ctrl_handler(DWORD dwCtrlType)

{

  g_exit = true;

  return TRUE;

}

 

intmain(int argc, char **argv)

{

  SetConsoleCtrlHandler(console_ctrl_handler,TRUE);

  initialize();

  while (!g_exit)

    do_a_piece_of_work();

  finalize();

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值