Windows 7
How to disable the Close
item of console window context menu?
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:
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With