Get console location and size in pixels

Asked

Viewed 41 times

2

Is there any way to get the size and location of the System.Console in pixels, don’t tiers? I’ve tried this method:

'Para o tamanho:
Dim X, Y As Integer
X = Console.WindowWidth * 8
Y = Console.WindowHeigth * 12
Dim final As Size = New Size(X, Y)
'8x12 por que cada caractere tem 8 por 12 pixels.

But I think, what if the user has changed the console source? Thank you already.

1 answer

1


You can use the function GetCurrentConsoleFont, information will be returned as the numeric index of the source in console source table and the structure COORD, which shall contain the information of width and height.

  1. Declare the namespace:

    Imports System.Runtime.InteropServices
    
  2. State the structures:

    Public Structure Coord
        Dim X As Short
        Dim Y As Short
    End Structure
    
    Public Structure _CONSOLE_FONT_INFO
        Dim nFont As Integer
        Dim dwFontSize As Coord
    End Structure
    
  3. Declare the duties:

    <DllImport("kernel32.dll", SetLastError:=True)> _
    Public Function GetStdHandle(ByVal nStdHandle As Integer) As Integer
    End Function
    
    <DllImport("kernel32.dll", SetLastError:=True)> _
    Public Function GetCurrentConsoleFont(ByVal hConsoleOutput As Integer,
                                          ByVal bMaximumWindow As Boolean,
                                          ByRef lpConsoleCurrentFont As _CONSOLE_FONT_INFO) As Boolean
    End Function
    
  4. Declare the constant:

    Private Const STD_OUTPUT_HANDLE As Integer = -11&
    
  5. In the main function, do:

    Sub Main()
        Dim CurrentFont As _CONSOLE_FONT_INFO
        Dim Coordenadas As Coord
        Dim hConsoleOut As Integer = GetStdHandle(STD_OUTPUT_HANDLE)
    
        Dim ObterFonte As Boolean = GetCurrentConsoleFont(hConsoleOut, False, CurrentFont)
        If (ObterFonte) Then
            Coordenadas = CurrentFont.dwFontSize
            Console.WriteLine("X: {0} / Y: {1}", Coordenadas.X, Coordenadas.Y)
        Else
            Console.WriteLine("Não foi possível obter as informações sobre a fonte deste Console.")
        End If
    
        Console.ReadKey()
    End Sub
    

For a wider range of information, use the function GetCurrentConsoleFontEx.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.