首页 > 解决方案 > 如何获取 Windows 控制台窗体的大小?

问题描述

我正在寻找一种方法来获取控制台实际窗口的大小(以像素为单位)。到目前为止,我发现的所有内容都是使用 winforms 或 WPF,这两种我都不使用。我不是在寻找如何获得控制台窗口内的大小,而是窗口本身有多大。

标签: c#.netconsole

解决方案


我在网上搜索,但没有发现任何有用的东西。

所有答案都返回任一字符数或全屏分辨率。

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;

推荐阅读