Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable the `Close` item of console window context menu?

Tags:

c++

c#

winapi

Windows 7
How to disable the Close item of console window context menu?

UPD

I use PInvoke from C#:

const uint MF_BYCOMMAND = 0x00000000;
const uint MF_GRAYED = 0x00000001;
const uint SC_CLOSE = 0xF060;
const uint MF_DISABLED = 0x00000002;

[DllImport("kernel32.dll")]
static extern IntPtr GetConsoleWindow();

[DllImport("user32.dll")]
static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);

[DllImport("User32.dll", SetLastError = true)]
static extern uint EnableMenuItem(IntPtr hMenu, uint itemId, uint uEnable);

...

// Disable the close button and "Close" context menu item of the Console window
IntPtr hwnd = GetConsoleWindow();
IntPtr hmenu = GetSystemMenu(hwnd, false);
uint hWindow = EnableMenuItem(hmenu, SC_CLOSE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED);

My code disables "X" button, but "Close" item is still enabled and can be launched:

enter image description here

like image 652
Andrey Bushman Avatar asked Oct 18 '22 12:10

Andrey Bushman


1 Answers

SC_CLOSE is the respective identifier to disable. EnableMenuItem disables X button and the menu item, however it appears that the trick does not work (older OSes?). Deletion of the menu item does work, including X box (non-client area handler presumably cannot check state of the menu item and applies disabled state; whereas disabled menu item is re-enabled and becomes available again).

const HMENU hMenu = GetSystemMenu(GetConsoleWindow(), FALSE);
//EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED);
DeleteMenu(hMenu, SC_CLOSE, MF_BYCOMMAND);

enter image description here

like image 169
Roman R. Avatar answered Oct 21 '22 06:10

Roman R.