我在网上搜索,但没有发现任何有用的东西。
所有答案都返回任一字符数或全屏分辨率。
Windows 控制台在历史上是 DOS shell 的模拟。
来自How to get the screen size of Console Application?:
using System.Management; // Need assembly reference added to project
Console.Write("Console resolution in char:");
Console.Write(Console.WindowWidth + "x" + Console.WindowHeight);
var scope = new ManagementScope();
scope.Connect();
var query = new ObjectQuery("SELECT * FROM Win32_VideoController");
using ( var searcher = new ManagementObjectSearcher(scope, query) )
foreach ( var result in searcher.Get() )
Console.WriteLine("Screen resolution in pixels: {0}x{1}",
result.GetPropertyValue("CurrentHorizontalResolution"),
result.GetPropertyValue("CurrentVerticalResolution"));
它返回当前视频驱动模式的屏幕分辨率。
Windows 命令行不再是 DOS 命令行,而是简化的 shell。
很多东西和很多 DOS 命令都丢失了。
您不能再在控制台本身中创建程序了。
命令行输出 API 现在非常简单和基本。
今天,控制台应用程序只能以字符形式知道其分辨率。
没有更高级的 API,也没有可用的中断。
Windows Me 之后,Windows DOS shell COMMAND.COM 已被命令提示符 CMD.EXE 抛弃。
没有简单的方法可以知道“托管”内部控制台的 Windows 的像素分辨率是多少。
using System.Diagnostics;
using System.Drawing;
using System.Runtime.InteropServices;
[DllImport("user32.dll")]
private static extern int GetWindowRect(IntPtr hwnd, out Rectangle rect);
Rectangle rect;
GetWindowRect(Process.GetCurrentProcess().MainWindowHandle, out rect);
Console.WriteLine($"Console window location: {rect.X}x{rect.Y}");
Console.WriteLine($"Console window resolution: {rect.Width}x{rect.Height}");
但结果不是很准确。
例如它显示:
Console window location: 187x174
Console window resolution: 1336x812
当实际分辨率为 1149x638 时...
而且这个控制台窗口的分辨率在每次运行时都会有所不同...
Console window location: 99x58
Console window resolution: 1248x696
Console window location: 143x116
Console window resolution: 1292x754
Console window location: 77x29
Console window resolution: 1226x667
Console window location: 187x174
Console window resolution: 1336x812
真正的控制台表单大小是:
RealWidth = rect.Width - rect.X;
RealHeight = rect.Height - rect.Y;