问题描述
我正在C#.NET中为控制台编写图像查看器.我的问题是控制台字体字符不是正方形.我将它们视为像素,当在屏幕上绘制时会拉伸图像.
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.
我想以某种方式读取有关当前使用的字体的字体信息,其中包括 width
, height
等属性...
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.
我玩了以下代码:
[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.
我仍然想使用类似 ConsoleFont
的结构来存储字体属性.但是 GetConsoleFontInfo(...)
并没有做到这一点...
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 :)
推荐答案
正确的解决方案是实现以下几行:
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...
这篇关于获取当前控制台字体信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!