Andrey Bushman
Andrey Bushman

Reputation: 12516

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

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

Upvotes: 5

Views: 2884

Answers (3)

Zrn-dev
Zrn-dev

Reputation: 169

HWND hwndConsole = ::GetConsoleWindow();
HMENU hMenu = ::GetSystemMenu(hwndConsole, FALSE);
::DeleteMenu(hMenu, SC_CLOSE, MF_BYCOMMAND);

enter image description here

Upvotes: 0

testuser012323
testuser012323

Reputation: 1

I just wrote a class library called librs you can download it on https://www.dllme.com/dll/files/librs_dll.html or http://plweb.pluginweb.ml/viewpage/librs.dll and you can write it librs.menucontrol.DisableAll(); has update.

Upvotes: -1

Roman Ryltsov
Roman Ryltsov

Reputation: 69706

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

Upvotes: 5

Related Questions