Changing font in a Console window in C#

前端 未结 4 883
迷失自我
迷失自我 2020-12-06 02:32

I have a program, written in C#, that uses characters not available in Raster fonts. So I want to change font to Lucida Console.

To change Console font programatical

4条回答
  •  不思量自难忘°
    2020-12-06 03:05

    There's two problems with the way you've defined those API calls.

    First, the documentation for SetCurrentConsoleFontEx says:

    lpConsoleCurrentFontEx

    A pointer to a CONSOLE_FONT_INFOEX structure that contains the font information.

    So the third parameter needs to be passed by reference:

    [DllImport("kernel32.dll", SetLastError = true)]
    static extern bool SetCurrentConsoleFontEx(
        IntPtr consoleOutput,
        bool maximumWindow,
        ref CONSOLE_FONT_INFO_EX consoleCurrentFontEx);
    

    and you need to call the method like this:

    SetCurrentConsoleFontEx(hnd, false, ref newInfo);
    

    Secondly, the FaceName field in the CONSOLE_FONT_INFO_EX structure is an array of Unicode characters. I had to specify the CharSet to get it to work:

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    internal unsafe struct CONSOLE_FONT_INFO_EX
    {
        internal uint cbSize;
        internal uint nFont;
        internal COORD dwFontSize;
        internal int FontFamily;
        internal int FontWeight;
        internal fixed char FaceName[LF_FACESIZE];
    }
    

提交回复
热议问题