Using Unicode font in C++ console app

后端 未结 3 1671
再見小時候
再見小時候 2020-12-29 13:46

How do I change the font in my C++ Windows console app?

It doesn\'t seem to use the font cmd.exe uses by default (Lucida Console). When I run my app through an exis

相关标签:
3条回答
  • 2020-12-29 14:27

    For Vista and above, there is SetCurrentConsoleFontEx, as already has been said.

    For 2K and XP, there is an undocumented function SetConsoleFont; e.g. read here.

    typedef BOOL (WINAPI *FN_SETCONSOLEFONT)(HANDLE, DWORD);
    FN_SETCONSOLEFONT SetConsoleFont;
    ..........
    HMODULE hm = GetModuleHandle(_T("KERNEL32.DLL"));
    SetConsoleFont = (FN_SETCONSOLEFONT) GetProcAddress(hm, "SetConsoleFont");
    // add error checking
    ..........
    
    SetConsoleFont(GetStdHandle(STD_OUTPUT_HANDLE), console_font_index);
    

    Now, console_font_index is an index into console font table, definition of which is unknown. However, console_font_index == 10 is known to identify Lucida Console (a Unicode font). I'm not sure how stable is this value across different OS versions.

    UPDATE

    After dutt's comment, I've run an experiment on a clean XP SP2 setup.

    • Initially, GetNumberOfConsoleFonts(), indeed, returns 10, and font indices 0..9 specify various raster fonts.

    • After I open a console with Lucida font selected in its properties (just once; I can close it immediately after opening but the effect is the same), suddenly GetNumberOfConsoleFonts() starts to return 12, and indices 10 and 11 select Lucida of different sizes.

    So it seems this trick worked for me when I played with it because I always had running at least one console app with Lucida font selected.

    Thus, for practical purposes, jon hanson's answer seems better. Besides offering better control, it actually works. :)

    0 讨论(0)
  • 2020-12-29 14:28

    Windows stores the cmd settings (including the font) in the registry using the exe path as the key. The root key is 'HKEY_CURRENT_USER\Console' so if you take a look in there with regedit you should see several sub-keys named after varous exe's.

    To copy the settings of an existing exe, you can export the key to a text file, then edit the file to change the key name to that of your exe, then reimport it.

    You can also progmatically modify the registry though i doubt that would take immediate effect w.r.t. to your console window.

    0 讨论(0)
  • 2020-12-29 14:46

    You could try the SetCurrentConsoleFontEx() function.

    0 讨论(0)
提交回复
热议问题