Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Prevent the console window from closing when red X is clicked

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 :) !!

like image 758
Aziz Mat Avatar asked Sep 02 '25 06:09

Aziz Mat


2 Answers

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

like image 82
bavaza Avatar answered Sep 04 '25 20:09

bavaza


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.

like image 26
Ajay Avatar answered Sep 04 '25 21:09

Ajay