开发者

Is it possible to get/set the console font size?

I have seen posts on changing console true type font and console colors (rgb) but nothing on setting or getting the console font size.

The reason I want to change the font size is because a grid is printed to the console, and the grid has many columns, so, it fits better with a smaller font. I'开发者_JS百科m wondering if it's possible to change it at runtime rather than allowing the default or configured fonts to take priority / override inheritance.


Maybe this article can help you

ConsoleHelper.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Drawing;

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

    public static class ConsoleHelper {
        [DllImport("kernel32")]
        public static extern bool SetConsoleIcon(IntPtr hIcon);

        public static bool SetConsoleIcon(Icon icon) {
            return SetConsoleIcon(icon.Handle);
        }

        [DllImport("kernel32")]
        private extern static bool SetConsoleFont(IntPtr hOutput, uint index);

        private enum StdHandle {
            OutputHandle = -11
        }

        [DllImport("kernel32")]
        private static extern IntPtr GetStdHandle(StdHandle index);

        public static bool SetConsoleFont(uint index) {
            return SetConsoleFont(GetStdHandle(StdHandle.OutputHandle), index);
        }

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

        [DllImport("kernel32")]
        private static extern uint GetNumberOfConsoleFonts();

        public static uint ConsoleFontsCount {
            get {
                return GetNumberOfConsoleFonts();
            }
        }

        public static ConsoleFont[] ConsoleFonts {
            get {
                ConsoleFont[] fonts = new ConsoleFont[GetNumberOfConsoleFonts()];
                if(fonts.Length > 0)
                    GetConsoleFontInfo(GetStdHandle(StdHandle.OutputHandle), false, (uint)fonts.Length, fonts);
                return fonts;
            }
        }

    }
}

Here is how to use it to list true type fonts for console,

static void Main(string[] args) {
   var fonts = ConsoleHelper.ConsoleFonts;
   for(int f = 0; f < fonts.Length; f++)
      Console.WriteLine("{0}: X={1}, Y={2}",
         fonts[f].Index, fonts[f].SizeX, fonts[f].SizeY);

   ConsoleHelper.SetConsoleFont(5);
   ConsoleHelper.SetConsoleIcon(SystemIcons.Information);
}

Crucial functions: SetConsoleFont, GetConsoleFontInfo and GetNumberOfConsoleFonts. They're undocumented, so use at your own risk.


In this thread I found a much more elegant solution that now works perfectly fine.

ConsoleHelper.cs:

using System;
using System.Runtime.InteropServices;

public static class ConsoleHelper
{
    private const int FixedWidthTrueType = 54;
    private const int StandardOutputHandle = -11;

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

    [return: MarshalAs(UnmanagedType.Bool)]
    [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    internal static extern bool SetCurrentConsoleFontEx(IntPtr hConsoleOutput, bool MaximumWindow, ref FontInfo ConsoleCurrentFontEx);

    [return: MarshalAs(UnmanagedType.Bool)]
    [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    internal static extern bool GetCurrentConsoleFontEx(IntPtr hConsoleOutput, bool MaximumWindow, ref FontInfo ConsoleCurrentFontEx);


    private static readonly IntPtr ConsoleOutputHandle = GetStdHandle(StandardOutputHandle);

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    public struct FontInfo
    {
        internal int cbSize;
        internal int FontIndex;
        internal short FontWidth;
        public short FontSize;
        public int FontFamily;
        public int FontWeight;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
        //[MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.wc, SizeConst = 32)]
        public string FontName;
    }

    public static FontInfo[] SetCurrentFont(string font, short fontSize = 0)
    {
        Console.WriteLine("Set Current Font: " + font);

        FontInfo before = new FontInfo
        {
            cbSize = Marshal.SizeOf<FontInfo>()
        };

        if (GetCurrentConsoleFontEx(ConsoleOutputHandle, false, ref before))
        {

            FontInfo set = new FontInfo
            {
                cbSize = Marshal.SizeOf<FontInfo>(),
                FontIndex = 0,
                FontFamily = FixedWidthTrueType,
                FontName = font,
                FontWeight = 400,
                FontSize = fontSize > 0 ? fontSize : before.FontSize
            };

            // Get some settings from current font.
            if (!SetCurrentConsoleFontEx(ConsoleOutputHandle, false, ref set))
            {
                var ex = Marshal.GetLastWin32Error();
                Console.WriteLine("Set error " + ex);
                throw new System.ComponentModel.Win32Exception(ex);
            }

            FontInfo after = new FontInfo
            {
                cbSize = Marshal.SizeOf<FontInfo>()
            };
            GetCurrentConsoleFontEx(ConsoleOutputHandle, false, ref after);

            return new[] { before, set, after };
        }
        else
        {
            var er = Marshal.GetLastWin32Error();
            Console.WriteLine("Get error " + er);
            throw new System.ComponentModel.Win32Exception(er);
        }
    }
}

This way you can just do:

ConsoleHelper.SetCurrentFont("Consolas", 10);


After running the application (Ctrl + F5), right-click the title of the Console (it should say something like C:Windows\system32\cmd.exe) and select properties. Choose the "Font" tab, and you'll see the option to adjust the size.


The console does not support changing font size at runtime. A list of the available methods for modifying the current console windows settings can be found on MSDN. My understanding is that this is because:

  1. The console is not a rich text interface, meaning it cannot display multiple fonts or font sizes.
  2. as Noldorin states, this is something that should be up to the user, for example a person with vision problems may elect for a large fontsize.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜