Windows 7
如何禁用Close控制台窗口上下文菜单项?
我使用 C# 中的 PInvoke:
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);
Run Code Online (Sandbox Code Playgroud)
我的代码禁用了“X”按钮,但“关闭”项仍处于启用状态并且可以启动:
SC_CLOSE是要禁用的相应标识符。EnableMenuItem禁用 X 按钮和菜单项,但似乎该技巧不起作用(较旧的操作系统?)。删除菜单项确实有效,包括 X 框(非客户区处理程序可能无法检查菜单项的状态并应用禁用状态;而禁用的菜单项将重新启用并再次可用)。
const HMENU hMenu = GetSystemMenu(GetConsoleWindow(), FALSE);
//EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED);
DeleteMenu(hMenu, SC_CLOSE, MF_BYCOMMAND);
Run Code Online (Sandbox Code Playgroud)