获取当前控制台字体信息

Get current console font info

我正在用 C# .NET 为控制台编写图像查看器。我的问题是控制台字体字符不是正方形。我将它们视为像素,这会在屏幕上绘制时拉伸图像。

我想以某种方式读取有关当前使用的字体的字体信息,具有 widthheight 等属性...

我找到了 this answer,但它似乎只列出了所有当前可用的字体。

我试过这段代码:

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct ConsoleFont
{
        public uint Index;
        public short SizeX, SizeY;
}

[DllImport("kernel32")]
private static extern bool GetConsoleFontInfo(IntPtr hOutput, [MarshalAs(UnmanagedType.Bool)]bool bMaximize, uint count, [MarshalAs(UnmanagedType.LPArray), Out] ConsoleFont[] fonts);

这不是return当前控制台使用的特定字体window。

我仍然想使用类似 ConsoleFont 结构的东西来存储字体属性。但是 GetConsoleFontInfo(...) 并没有按照所说的那样做...

如果有人知道怎么做,请告诉我:)

正确的解决方案是实施这些行:

        const int STD_OUTPUT_HANDLE = -11;
        [DllImport("kernel32.dll", SetLastError = true)]
        static extern IntPtr GetStdHandle(int nStdHandle);

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        public class CONSOLE_FONT_INFO_EX
        {
            private int cbSize;
            public CONSOLE_FONT_INFO_EX()
            {
                cbSize = Marshal.SizeOf(typeof(CONSOLE_FONT_INFO_EX));
            }
            public int FontIndex;
            public COORD dwFontSize;
            public int FontFamily;
            public int FontWeight;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
            public string FaceName;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct COORD
        {
            public short X;
            public short Y;

            public COORD(short X, short Y)
            {
                this.X = X;
                this.Y = Y;
            }
        };

        [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        extern static bool GetCurrentConsoleFontEx(IntPtr hConsoleOutput, bool bMaximumWindow, [In, Out] CONSOLE_FONT_INFO_EX lpConsoleCurrentFont);

然后只需读取当前控制台字体信息,如:

CONSOLE_FONT_INFO_EX currentFont = new CONSOLE_FONT_INFO_EX();
GetCurrentConsoleFontEx(GetStdHandle(STD_OUTPUT_HANDLE), false, currentFont);

// currentFont does now contain all the information about font size, width and height etc...