在C#控制台应用中,如何锁定全屏后的控制台窗口?
锁定最大化后的C#控制台窗口,禁止调整大小与移动
要实现锁定最大化控制台窗口、禁止用户调整大小或移动的需求,你需要通过Windows API修改窗口样式,移除允许调整大小和移动的相关样式位。以下是完整的实现代码:
using System; using System.Runtime.InteropServices; class Program { #region Dll Import [DllImport("user32.dll")] private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); [DllImport("kernel32.dll")] private static extern IntPtr GetConsoleWindow(); [DllImport("user32.dll", SetLastError = true)] private static extern IntPtr GetWindowLongPtr(IntPtr hWnd, int nIndex); [DllImport("user32.dll", SetLastError = true)] private static extern IntPtr SetWindowLongPtr(IntPtr hWnd, int nIndex, IntPtr dwNewLong); [DllImport("user32.dll")] private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags); #endregion private const int SW_SHOWMAXIMIZED = 3; private const int GWL_STYLE = -16; private const uint WS_THICKFRAME = 0x00040000; private const uint WS_SYSMENU = 0x00080000; private const uint SWP_FRAMECHANGED = 0x0020; private const uint SWP_NOMOVE = 0x0002; private const uint SWP_NOSIZE = 0x0001; private const uint SWP_NOZORDER = 0x0004; static void Main() { IntPtr hWnd = GetConsoleWindow(); if (hWnd != IntPtr.Zero) { // 最大化窗口 ShowWindow(hWnd, SW_SHOWMAXIMIZED); // 获取当前窗口样式 IntPtr currentStyle = GetWindowLongPtr(hWnd, GWL_STYLE); // 移除允许调整大小的边框和系统菜单(包含移动/大小选项) uint newStyle = (uint)currentStyle & ~(WS_THICKFRAME | WS_SYSMENU); SetWindowLongPtr(hWnd, GWL_STYLE, (IntPtr)newStyle); // 刷新窗口,确保样式变更生效 SetWindowPos(hWnd, IntPtr.Zero, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER); } } }
关键逻辑说明
- 移除
WS_THICKFRAME:该样式位控制窗口是否带有可拖动调整大小的边框,移除后用户无法通过拖动边框改变窗口大小。 - 移除
WS_SYSMENU:该样式位对应窗口标题栏的右键菜单(包含“移动”“大小”选项),同时会隐藏标题栏的最大化/最小化按钮,彻底阻断用户通过系统菜单调整窗口状态的路径。 - 调用
SetWindowPos:强制窗口重新绘制边框,确保样式修改立即生效,参数组合保证仅刷新样式,不改变窗口的位置、大小和层级。
内容的提问来源于stack exchange,提问作者Ill Magnus
相关产品推荐
相关产品推荐

