Get current console font info

给你一囗甜甜゛ 提交于 2021-02-08 04:45:53

问题


I am writing an Image Viewer in C# .NET for the console. My problem is that the console font characters are not squares. And I'm treating them as pixels, this stretches the images when drawn on screen.

I want to somehow read the font information about the currently used font, with width, height etc properties...

I found this answer, but it seems like it just lists all the currently available fonts.

I played around with this code:

[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);

This did not return the specific font used in the current console window.

I still want to use something like the ConsoleFont struct for storing font properties. But the GetConsoleFontInfo(...) does not do this as said...

Please if someone knows how to do this, tell me :)


回答1:


The correct solution was to implement these lines:

        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);

And then just read the current console font information like:

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... 


来源:https://stackoverflow.com/questions/56428050/get-current-console-font-info

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!