c# - 如何获取 Windows 控制台窗体的大小?
问题描述
我正在寻找一种方法来获取控制台实际窗口的大小(以像素为单位)。到目前为止,我发现的所有内容都是使用 winforms 或 WPF,这两种我都不使用。我不是在寻找如何获得控制台窗口内的大小,而是窗口本身有多大。
解决方案
我在网上搜索,但没有发现任何有用的东西。
所有答案都返回任一字符数或全屏分辨率。
Windows 控制台在历史上是 DOS shell 的模拟。
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 外壳 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;
推荐阅读
- javascript - 来自 Firestore 的推送通知
- javascript - 某些命令的计时器
- sorting - awk 排序计数值求和重复和转置列
- entity-framework-core - 脚手架现有数据库 EF core 2.X 后更新模型
- vb.net - VSTO Outlook.Recipients 值显示外部电子邮件地址与内部电子邮件地址不同
- java - 在 Google App Engine 上从 Java 7 迁移到 Java 8 时出现内存错误/500 错误
- php - Laravel:仅当日期存在时,我如何验证日期?
- bash - 脚本在远程主机上运行 pv 命令 - 所有输出都按预期在本地显示,除了 pv 进度条
- c++ - 如何将 _ITERATOR_DEBUG_LEVEL 添加到 CMake?
- javascript - 复杂对象数组合并