问询:C#控制台调用Console.SetWindowSize无法修改终端窗口大小
解决Console.SetWindowSize()在Windows 11 + VS2019中失效的方案
方法1:切换到传统控制台模式
- 右键你的.NET Framework控制台项目,选择属性
- 进入调试选项卡,找到控制台类型下拉框
- 选择传统控制台,保存设置后重新运行项目
- 该方法恢复旧版控制台环境,原生
Console.SetWindowSize()即可正常生效
方法2:通过Windows API强制调整窗口
如果传统控制台模式仍不生效,可直接调用系统API绕过.NET限制:
首先添加API声明和工具类:
using System.Runtime.InteropServices; public static class ConsoleWindowUtility { [DllImport("user32.dll")] private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int width, int height, uint flags); [DllImport("kernel32.dll")] private static extern IntPtr GetConsoleWindow(); private const uint SWP_NOMOVE = 0x0002; private const uint SWP_NOZORDER = 0x0004; public static void Resize(int targetWidth, int targetHeight) { var consoleHandle = GetConsoleWindow(); // 按字符尺寸换算窗口像素(默认字符宽8px、高16px,可按需调整) SetWindowPos(consoleHandle, IntPtr.Zero, 0, 0, targetWidth * 8, targetHeight * 16, SWP_NOMOVE | SWP_NOZORDER); } }
然后在主函数中替换原有调用:
static void Main(string[] args) { ConsoleWindowUtility.Resize(10, 10); Console.WriteLine("Hello world"); Console.ReadLine(); }
方法3:先调整缓冲区大小
窗口尺寸不能超过控制台缓冲区的尺寸,否则设置会失效,可先同步调整缓冲区:
static void Main(string[] args) { // 确保缓冲区尺寸不小于目标窗口尺寸 Console.SetBufferSize(10, 10); Console.SetWindowSize(10, 10); Console.WriteLine("Hello world"); Console.ReadLine(); }
注意:若缓冲区原有尺寸大于目标值,可跳过SetBufferSize,但建议同步设置避免异常。
内容的提问来源于stack exchange,提问作者Lou
相关产品推荐
相关产品推荐

