C++ Prevent the console window from closing when r

2019-04-14 14:43发布

I'm developing a simple C++ console application without classes & objects.
Is there any method or function to prevent the console from closing when red X button is clicked ?
I'm using Visual Studio C++ Express 2010 : A simple console application which containes only main.cpp file. Thank you for answering my question :) !!

5条回答
虎瘦雄心在
2楼-- · 2019-04-14 15:01

You could always use signals:

#include <cstdio>
void my_handler(int param) {
  main();
}
int main() {
  signal(SIGABRT, my_handler);
  signal(SIGTERM, my_handler);
  return 0;
}  

You should obviously allow an option for the user to close the app, by changing my_handler. my_handler calls main, so whenever the program is closed, my_handler is called, so therefore main is called.

查看更多
我想做一个坏孩纸
3楼-- · 2019-04-14 15:02

It is possible to trap the close message for a window and prevent it from closing, if you are receiving messages for the window. Unfortunately a console is independent of the program running within it and you don't have that kind of control.

查看更多
时光不老,我们不散
4楼-- · 2019-04-14 15:05

You can use SetConsoleCtrlHandler to control the console-window. You need to write up a callback to handle events (such as CTRL_CLOSE_EVENT). You may also use GetConsoleWindow function to get the window-handle, and handle window messages. I have done controlling the window with former method, and not sure about handling specific window message (via window-handle).

Refer Console Functions.

查看更多
可以哭但决不认输i
5楼-- · 2019-04-14 15:09

This worked for me:

#include "conio.h"
void main()
{
    HWND hwnd = GetConsoleWindow();
    HMENU hmenu = GetSystemMenu(hwnd, FALSE);
    EnableMenuItem(hmenu, SC_CLOSE, MF_GRAYED);
}

While we're at it, to re-enable the button:

EnableMenuItem(hmenu, SC_CLOSE, MF_ENABLED);

... and to set the window's title:

char consoleTitle[256];
wsprintf(consoleTitle, _T("My little window"));
SetConsoleTitle((LPCTSTR)consoleTitle);

I saw that most references used DeleteMenu and not EnableMenuItem. I preffer the later, as you get more control (enable/disable/greyed-out etc.). For full options, take a look at MSDN Console Functions and Menu Functions

查看更多
做个烂人
6楼-- · 2019-04-14 15:22

Sorry this isn't a comment, I don't have enough points to comment yet.

Can't you just remove the button in the properties for the form?

查看更多
登录 后发表回答