elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.


Tema destacado: Estamos en la red social de Mastodon


  Mostrar Mensajes
Páginas: [1] 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ... 1254
1  Programación / Scripting / [APORTE] [PowerShell] [VBS] Mostrar el tiempo transcurrido desde el último arranque del sistema. en: 8 Septiembre 2025, 00:57 am
El siguiente script, desarrollado en PowerShell, crea una ventana gráfica (Form) que muestra, en tiempo real, el tiempo transcurrido desde el último arranque (uptime) del sistema:


( Nota: el efecto de parpadeo o flickering es debido a la captura del GIF animado )

Es un script muy simple y su único cometido es ese. Yo lo utilizo en una máquina virtual, aunque cada persona podría encontrarle usos diferentes.

El código:
Código
  1. Add-Type -AssemblyName System.Drawing
  2. Add-Type -AssemblyName System.Windows.Forms
  3.  
  4. Add-Type @"
  5. using System;
  6. using System.Runtime.InteropServices;
  7.  
  8. public static class WinAPI {
  9.    [DllImport("kernel32.dll")]
  10.    public static extern IntPtr GetConsoleWindow();
  11.  
  12.    [DllImport("user32.dll")]
  13.    public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
  14.  
  15.    [DllImport("shell32.dll", CharSet=CharSet.Unicode)]
  16.    public static extern int ExtractIconEx(string lpszFile, int nIconIndex, out IntPtr phiconLarge, out IntPtr phiconSmall, int nIcons);
  17.  
  18.    [DllImport("user32.dll", CharSet=CharSet.Auto)]
  19.    public static extern bool DestroyIcon(IntPtr handle);
  20. }
  21. "@
  22.  
  23. # --- SINGLE INSTANCE CHECK THROUGH MUTEX ---
  24. $mutexName = "Global\ComputerUptimeFormMutex"
  25. $createdNew = $false
  26. $mutex = New-Object System.Threading.Mutex($true, $mutexName, [ref]$createdNew)
  27.  
  28. if (-not $createdNew) {
  29.    [System.Windows.Forms.MessageBox]::Show(
  30.        "Only one instance of this program is allowed.",
  31.        "Computer Uptime",
  32.        [System.Windows.Forms.MessageBoxButtons]::OK,
  33.        [System.Windows.Forms.MessageBoxIcon]::Stop
  34.    )
  35.    exit
  36. }
  37.  
  38. # --- HIDE CURRENT POWERSHELL CONSOLE ---
  39. $SW_HIDE = 0
  40. $hWnd = [WinAPI]::GetConsoleWindow()
  41. [WinAPI]::ShowWindow($hWnd, $SW_HIDE) | Out-Null
  42.  
  43. # --- CREATE THE FORM ---
  44. $form                 = New-Object System.Windows.Forms.Form
  45. $form.Text            = "Computer Uptime"
  46. $form.Size            = New-Object System.Drawing.Size(350, 150)
  47. $form.StartPosition   = "CenterScreen"
  48. $form.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedDialog
  49. $form.MaximizeBox     = $false
  50. $form.MinimizeBox     = $true
  51. $form.Padding         = New-Object System.Windows.Forms.Padding(4)
  52. $form.DoubleBuffered  = $true
  53.  
  54. # --- SET FORM ICON ---
  55. $shell32   = "$env:SystemRoot\System32\shell32.dll"
  56. $hLarge    = [IntPtr]::Zero
  57. $hSmall    = [IntPtr]::Zero
  58. $iconIndex = 265 # A clock icon in Windows 10.
  59.  
  60. [WinAPI]::ExtractIconEx($shell32, $iconIndex, [ref]$hLarge, [ref]$hSmall, 1) | Out-Null
  61.  
  62. if ($hSmall -ne [IntPtr]::Zero) {
  63.    $form.Icon = [System.Drawing.Icon]::FromHandle($hSmall)
  64. }
  65.  
  66. # --- LABEL TO DISPLAY UPTIME ---
  67. $label                = New-Object System.Windows.Forms.Label
  68. $label.Font           = New-Object System.Drawing.Font("Segoe UI", 14, [System.Drawing.FontStyle]::Bold)
  69. $label.Dock           = [System.Windows.Forms.DockStyle]::Fill
  70. $label.TextAlign      = [System.Drawing.ContentAlignment]::MiddleCenter
  71. $label.AutoSize       = $false
  72. $label.DoubleBuffered = $true
  73. $form.Controls.Add($label)
  74.  
  75. # --- GET SYSTEM INFORMATION FROM WMI ---
  76. $os           = Get-CimInstance Win32_OperatingSystem
  77. $bootTime     = $os.LastBootUpTime
  78. $computerName = $os.CSName
  79.  
  80. # --- TIMER TO UPDATE UPTIME ---
  81. $timer = New-Object System.Windows.Forms.Timer
  82. $timer.Interval = 100
  83. $timer.Add_Tick({
  84.    $uptime       = (Get-Date) - $bootTime
  85.    $minutes      = $uptime.Minutes.ToString("00")
  86.    $seconds      = $uptime.Seconds.ToString("00")
  87.    $milliseconds = $uptime.Milliseconds.ToString("000")
  88.    $label.Text   = "$computerName`n`n$($uptime.Days) days — $($uptime.Hours)h : $($minutes)m : $($seconds)s : $($milliseconds)ms"
  89. })
  90. $timer.Start()
  91.  
  92. # --- RELEASE ICON HANDLES AND MUTEX WHEN FORM GETS CLOSED ---
  93. $form.Add_FormClosed({
  94.    if ($hSmall -ne [IntPtr]::Zero) { [WinAPI]::DestroyIcon($hSmall) }
  95.    if ($hLarge -ne [IntPtr]::Zero) { [WinAPI]::DestroyIcon($hLarge) }
  96.    $mutex.ReleaseMutex()
  97. })
  98.  
  99. # --- SHOW THE FORM ---
  100. [void]$form.ShowDialog()

PD: 80% del código fue hecho por ChatGPT (considero una pérdida de tiempo diseñar manualmente el form en texto plano, además de buscar y añadir las definiciones de la API de Windows, cosas que puede hacer una IA perfectamente y en menos de un segundo), 20% edición y revisión humana. De todas formas, esto no tendría ningún mérito haberlo hecho a mano en un 100%, pero aun así quiero ser honesto con lo que comparto.



Por último, les muestro una especie de equivalente mucho más básico hecho con VisualBasic Script (VBS). El siguiente código tan solo muestra un cuadro de mensaje, sin actualización en tiempo real de ningún tipo.

Código
  1. Option Explicit
  2.  
  3. Dim oneMinute, oneHour, oneDay: oneMinute = 60: oneHour = 3600: oneDay = 86400
  4. Dim objWMIService, colOperatingSystems, objOperatingSystem
  5. Dim computerName, lastBootUpTime, upTime
  6.  
  7. Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
  8. Set colOperatingSystems = objWMIService.ExecQuery("Select * from Win32_OperatingSystem")
  9.  
  10. For Each objOperatingSystem In colOperatingSystems
  11.    computerName = objOperatingSystem.CSName
  12.    lastBootUpTime = objOperatingSystem.LastBootUpTime
  13.    lastBootUpTime = CDate(Mid(lastBootUpTime, 1, 4) & "/" & Mid(lastBootUpTime, 5, 2) & "/" & Mid(lastBootUpTime, 7, 2) & " " & _
  14.                           Mid(lastBootUpTime, 9, 2) & ":" & Mid(lastBootUpTime, 11, 2) & ":" & Mid(lastBootUpTime, 13, 2))
  15.  
  16.    upTime = DateDiff("s", lastBootUpTime, Now)
  17.    MsgBox computerName & vbCrLf & vbCrLf  & _
  18.           upTime \ oneDay & " days ~ " & _
  19.           (upTime Mod oneDay) \ oneHour & "h : " & _
  20.           (upTime Mod oneHour) \ oneMinute & "m : " & _
  21.           upTime Mod oneMinute & "s", vbInformation, "Computer Uptime"
  22.  
  23. Next
  24.  
  25. WScript.Quit(0)
2  Foros Generales / Sugerencias y dudas sobre el Foro / ¿Han recibido mi e-mail? en: 7 Septiembre 2025, 22:20 pm
Hola. Envié un correo a varias direcciones que supuestamente son del staff de elhacker.net, lo siento por parecer pesado pero me quitarían una preocupación de encima si alguien me confirmase que han recibido el correo. Por que no sé si en alguna (o todas) esas direcciones de correo tal vez me tienen bloqueado por discusiones ocurridas en el pasado.

El e-mail que les he enviado es en relación a mi petición para eliminar un e-mail que aparece en un post del sitio web https://forum.elhacker.net/, y ahí explico todos los detalles...

Este es el segundo hilo que abro al respecto, y sé que solo han pasado dos días, pero me preocupo con facilidad, sobre todo cuando el primer hilo lo han borrado sin ofrecer respuesta, y por el momento nadie se ha puesto en contacto conmigo. (¿ustedes suelen fijarse en los hilos borrados de la papelera?).

Por favor tengan en cuenta que yo desconozco quien tiene acceso para administrar ese sitio web, no sé si solamente el-brujo es capaz, y a lo mejor por eso nadie ha querido ofrecerme una respuesta ni contactar conmigo. En ese caso díganmelo y contactaré con él por WhatsApp, como ya os dije en una ocasión no quiero recurrir a eso sin su consentimiento para terminar molestando... si no fuese realmente necesario.

Ya he enviado la correspondiente solicitud de retirada de contenido a Google para ver si ellos pueden eliminar ese resultado de búsqueda donde aparece el post de https://forum.elhacker.net/, pero desconozco cuanto tiempo puede tardar en resolverse este tipo de denuncia, y al final pueden decidir no hacer nada al respecto, así que por favor necesito que ustedes me ayuden con lo que está en vuestras manos poder hacer.

Quiero pensar que en esta ocasión no me perciben como Elektro "el que le cae mal a todo el staff", sino como una persona que simplemente solicita algo tan razonable como poder eliminar cierta información personal que no debería ser accesible de forma pública como lo es desde ese sitio web, y a su vez desde un motor de búsqueda tipo Google.

Si ustedes revocasen mi baneo en ese sitio web, y suponiendo que yo pudiera editar un post de esa antigüedad, pues podría hacer yo mismo la tarea de eliminar ese e-mail y así no les quitaría más tiempo con este asunto.

Gracias de antemano.
3  Media / Multimedia / Re: comprobar estado de video en: 5 Septiembre 2025, 19:02 pm
yo me refiero cuando metes una pelicula dvd en clonedvd la comprueba

No sé a qué te refieres exactamente. De todas formas, probablemente lo que ese programa haga (y cualquier otro, como por ejemplo MakeMKV) sea una validación inicial para determinar que el formato y estructura del DVD que estás intentando cargar coincida con lo que se espera de un DVD de video, y tras esa validación inicial luego identificará la cantidad de pistas de video, audio y subtítulos, los títulos, etc, pero dudo mucho que haga algo como "comprobar el estado" del video.

El título que le asignaste al hilo es: "comprobar estado de video", refiriéndote a archivos MKV y MP4, así que voy a responder a eso:

Para comprobar si un archivo en formato MKV o MP4 está corrupto, es suficiente con cargar el archivo en el programa MKVToolnix (descarga) y presionar el botón "Iniciar multiplexado". Si la operación se completa sin ningún registro de avisos ni errores, entonces las pistas del contenedor MKV/MP4 están en perfectas condiciones.

Atentamente,
Elektro.
4  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets) en: 3 Septiembre 2025, 01:34 am
Métodos universales para trabajar (los últimos) aspectos básicos con fuentes de texto (.ttf y .otf)...

Funciones 'UtilFonts.GetFontGlyphOutlineData' y 'FontExtensions.GetGlyphOutlineData'

    Sirven para obtener los datos crudos de contorno (outline) de un glifo para un carácter específico en una fuente.

    Devuelven un array de bytes que representa la forma vectorial del glifo en el formato solicitado (Native o Bezier).

    Estos datos se pueden usar como base para comparaciones de glifos.

Funciones 'UtilFonts.FontGlyphOutlinesAreEqual' y 'FontExtensions.GlyphOutlinesAreEqual'

    Sirven para comparar si dos fuentes producen los mismos datos de contorno (outline) de un glifo para un carácter específico.

Funciones 'UtilFonts.GetFontGlyphOutlineSimilarity' y 'FontExtensions.GetGlyphOutlineSimilarity'

    Sirven para calcular un índice de similitud entre los contornos de un glifo para un carácter específico en dos fuentes distintas.

    Se puede usar cuando se quiere medir cuán parecidos son los glifos entre dos fuentes, en lugar de solo saber si son exactamente iguales.



El código fuente

⚠️ Importante: Para poder utilizar este código se requieren algunas definiciones de la API de Windows que he compartido en el post anterior a este. No lo comparto aquí de nuevo para evitar repetir código y evitar que este post quede demasiado grande y tedioso de leer. 🙏

Código
  1. Public Class UtilFonts
  2.  
  3.    ''' <summary>
  4.    ''' Prevents a default instance of the <see cref="UtilFonts"/> class from being created.
  5.    ''' </summary>
  6.    Private Sub New()
  7.    End Sub
  8.  
  9.    ''' <summary>
  10.    ''' Retrieves the raw outline data for a given glyph from the specified font file.
  11.    ''' <para></para>
  12.    ''' This function calls <see cref="DevCase.Win32.NativeMethods.GetGlyphOutline"/> in background
  13.    ''' to retrieve outline data with the requested <paramref name="format"/>.
  14.    ''' </summary>
  15.    '''
  16.    ''' <param name="fontFile">
  17.    ''' Path to the font file from which the glyph will be obtained.
  18.    ''' </param>
  19.    '''
  20.    ''' <param name="ch">
  21.    ''' The character whose glyph outline will be requested.
  22.    ''' </param>
  23.    '''
  24.    ''' <param name="format">
  25.    ''' The format in which the glyph outline will be retrieved.
  26.    ''' <para></para>
  27.    ''' This value only can be <see cref="GetGlyphOutlineFormat.Native"/> or <see cref="GetGlyphOutlineFormat.Bezier"/>.
  28.    ''' <para></para>
  29.    ''' Note: callers must interpret the returned byte array based on the selected format.
  30.    ''' </param>
  31.    '''
  32.    ''' <param name="matrix">
  33.    ''' An optional <see cref="GlyphOutlineMatrix2"/> used to transform the glyph outline.
  34.    ''' <para></para>
  35.    ''' If no value is provided or default structure is passed, an identity matrix
  36.    ''' will be used (see: <see cref="GlyphOutlineMatrix2.GetIdentityMatrix()"/>),
  37.    ''' where the transfromed graphical object is identical to the source object.
  38.    ''' </param>
  39.    '''
  40.    ''' <returns>
  41.    ''' A <see cref="Byte"/> array containing the raw glyph outline data with the requested <paramref name="format"/>.
  42.    ''' <para></para>
  43.    ''' Returns <see langword="Nothing"/> if the glyph is empty in the specified font.
  44.    ''' </returns>
  45.    '''
  46.    ''' <exception cref="FileNotFoundException">
  47.    ''' Thrown when the font file is not found.
  48.    ''' </exception>
  49.    <DebuggerStepThrough>
  50.    Public Shared Function GetFontGlyphOutlineData(fontFile As String, ch As Char, format As GetGlyphOutlineFormat,
  51.                                                   Optional matrix As GlyphOutlineMatrix2 = Nothing) As Byte()
  52.  
  53.        If Not File.Exists(fontFile) Then
  54.            Throw New FileNotFoundException("Font file not found.", fileName:=fontFile)
  55.        End If
  56.  
  57.        Using pfc As New PrivateFontCollection()
  58.            pfc.AddFontFile(fontFile)
  59.  
  60.            Using f As New Font(pfc.Families(0), emSize:=1)
  61.                Return FontExtensions.GetGlyphOutlineData(f, ch, format, matrix)
  62.            End Using
  63.        End Using
  64.    End Function
  65.  
  66.    ''' <summary>
  67.    ''' Determines whether the glyph outline for the specified character is identical in two font files.
  68.    ''' </summary>
  69.    '''
  70.    ''' <param name="firstFontFile">
  71.    ''' Path to the first font file to compare.
  72.    ''' </param>
  73.    '''
  74.    ''' <param name="secondFontFile">
  75.    ''' Path to the second font file to compare.
  76.    ''' </param>
  77.    '''
  78.    ''' <param name="ch">
  79.    ''' The character whose glyph outline will be compared between the two fonts.
  80.    ''' </param>
  81.    '''
  82.    ''' <returns>
  83.    ''' <see langword="True"/> if both fonts produce identical outlines for the specified glyph.
  84.    ''' <para></para>
  85.    ''' <see langword="False"/> if the outlines differ or if one of the fonts has an empty glyph.
  86.    ''' If the glyph outlines are empty in both fonts, returns <see langword="True"/>.
  87.    ''' </returns>
  88.    '''
  89.    ''' <exception cref="FileNotFoundException">
  90.    ''' Thrown when one of the font files is not found.
  91.    ''' </exception>
  92.    <DebuggerStepThrough>
  93.    Public Shared Function FontGlyphOutlinesAreEqual(firstFontFile As String, secondFontFile As String, ch As Char) As Boolean
  94.  
  95.        If Not File.Exists(firstFontFile) Then
  96.            Throw New FileNotFoundException("First font file not found.", fileName:=firstFontFile)
  97.        End If
  98.  
  99.        If Not File.Exists(secondFontFile) Then
  100.            Throw New FileNotFoundException("Second ont file not found.", fileName:=secondFontFile)
  101.        End If
  102.  
  103.        Using firstPfc As New PrivateFontCollection(),
  104.              secondPfc As New PrivateFontCollection()
  105.  
  106.            firstPfc.AddFontFile(firstFontFile)
  107.            secondPfc.AddFontFile(secondFontFile)
  108.  
  109.            Using firstFont As New Font(firstPfc.Families(0), emSize:=1),
  110.                  secondFont As New Font(secondPfc.Families(0), emSize:=1)
  111.  
  112.                Return FontExtensions.GlyphOutlineIsEqualTo(firstFont, secondFont, ch)
  113.            End Using
  114.        End Using
  115.    End Function
  116.  
  117.    ''' <summary>
  118.    ''' Computes a similarity score between the glyph outline for the specified character in two font files.
  119.    ''' </summary>
  120.    '''
  121.    ''' <param name="firstFontFile">
  122.    ''' Path to the first font file to compare.
  123.    ''' </param>
  124.    '''
  125.    ''' <param name="secondFontFile">
  126.    ''' Path to the second font file to compare.
  127.    ''' </param>
  128.    '''
  129.    ''' <param name="ch">
  130.    ''' The character whose glyph outline will be compared between the two fonts.
  131.    ''' </param>
  132.    '''
  133.    ''' <returns>
  134.    ''' A <see cref="Single"/> value between 0.0 and 1.0 representing the similarity
  135.    ''' (the number of matching bytes in the outline data) of the glyph outlines.
  136.    ''' <para></para>
  137.    ''' If one of the fonts has an empty glyph, returns 0. If the glyph outlines are empty in both fonts, returns 1.
  138.    ''' </returns>
  139.    '''
  140.    ''' <exception cref="FileNotFoundException">
  141.    ''' Thrown when one of the font files is not found.
  142.    ''' </exception>
  143.    <DebuggerStepThrough>
  144.    Public Shared Function GetFontGlyphOutlineSimilarity(firstFontFile As String, secondFontFile As String, ch As Char) As Single
  145.  
  146.        If Not File.Exists(firstFontFile) Then
  147.            Throw New FileNotFoundException("First font file not found.", fileName:=firstFontFile)
  148.        End If
  149.  
  150.        If Not File.Exists(secondFontFile) Then
  151.            Throw New FileNotFoundException("Second ont file not found.", fileName:=secondFontFile)
  152.        End If
  153.  
  154.        Using firstPfc As New PrivateFontCollection(),
  155.              secondPfc As New PrivateFontCollection()
  156.  
  157.            firstPfc.AddFontFile(firstFontFile)
  158.            secondPfc.AddFontFile(secondFontFile)
  159.  
  160.            Using firstFont As New Font(firstPfc.Families(0), emSize:=1),
  161.                  secondFont As New Font(secondPfc.Families(0), emSize:=1)
  162.  
  163.                Return FontExtensions.GetGlyphOutlineSimilarity(firstFont, secondFont, ch)
  164.            End Using
  165.        End Using
  166.    End Function
  167.  
  168. End Class

y:

Código
  1. Module FontExtensions
  2.  
  3.    ''' <summary>
  4.    ''' Retrieves the raw outline data for a given glyph from the specified <see cref="System.Drawing.Font"/>.
  5.    ''' <para></para>
  6.    ''' This function calls <see cref="DevCase.Win32.NativeMethods.GetGlyphOutline"/> in background
  7.    ''' to retrieve outline data with the requested <paramref name="format"/>.
  8.    ''' </summary>
  9.    '''
  10.    ''' <param name="font">
  11.    ''' The <see cref="System.Drawing.Font"/> object from which the glyph will be obtained.
  12.    ''' </param>
  13.    '''
  14.    ''' <param name="ch">
  15.    ''' The character whose glyph outline will be requested.
  16.    ''' </param>
  17.    '''
  18.    ''' <param name="format">
  19.    ''' The format in which the glyph outline will be retrieved.
  20.    ''' <para></para>
  21.    ''' This value only can be <see cref="GetGlyphOutlineFormat.Native"/> or <see cref="GetGlyphOutlineFormat.Bezier"/>.
  22.    ''' <para></para>
  23.    ''' Note: callers must interpret the returned byte array based on the selected format.
  24.    ''' </param>
  25.    '''
  26.    ''' <param name="matrix">
  27.    ''' An optional <see cref="GlyphOutlineMatrix2"/> used to transform the glyph outline.
  28.    ''' <para></para>
  29.    ''' If no value is provided or default structure is passed, an identity matrix
  30.    ''' will be used (see: <see cref="GlyphOutlineMatrix2.GetIdentityMatrix()"/>),
  31.    ''' where the transfromed graphical object is identical to the source object.
  32.    ''' </param>
  33.    '''
  34.    ''' <returns>
  35.    ''' A <see cref="Byte"/> array containing the raw glyph outline data with the requested <paramref name="format"/>.
  36.    ''' <para></para>
  37.    ''' Returns <see langword="Nothing"/> if the glyph is empty in the specified <paramref name="font"/>.
  38.    ''' </returns>
  39.    '''
  40.    ''' <exception cref="ArgumentNullException">
  41.    ''' Thrown when <paramref name="font"/> is <see langword="Nothing"/>.
  42.    ''' </exception>
  43.    '''
  44.    ''' <exception cref="ArgumentException">
  45.    ''' Thrown when the specified <paramref name="format"/> is invalid to request glyph outline data.
  46.    ''' </exception>
  47.    '''
  48.    ''' <exception cref="System.ComponentModel.Win32Exception">
  49.    ''' Thrown when a Win32 error occurs during font or device context operations.
  50.    ''' </exception>
  51.    <Extension>
  52.    <EditorBrowsable(EditorBrowsableState.Always)>
  53.    <DebuggerStepThrough>
  54.    Public Function GetGlyphOutlineData(font As Font, ch As Char, format As GetGlyphOutlineFormat,
  55.                                        Optional matrix As GlyphOutlineMatrix2 = Nothing) As Byte()
  56.  
  57.        If font Is Nothing Then
  58.            Throw New ArgumentNullException(paramName:=NameOf(font))
  59.        End If
  60.  
  61.        If format <> GetGlyphOutlineFormat.Native AndAlso
  62.           format <> GetGlyphOutlineFormat.Bezier Then
  63.  
  64.            Dim msg As String = $"The specified format '{format}' does not produce glyph outline data. " & Environment.NewLine &
  65.                                $"Use '{NameOf(GetGlyphOutlineFormat.Native)}' or '{NameOf(GetGlyphOutlineFormat.Bezier)}' " &
  66.                                "formats to request glyph outline data."
  67.  
  68.            Throw New ArgumentException(msg, paramName:=NameOf(format))
  69.        End If
  70.  
  71.        Dim hdc As IntPtr
  72.        Dim hFont As IntPtr
  73.        Dim oldObj As IntPtr
  74.  
  75.        Dim win32Err As Integer
  76.  
  77.        Try
  78.            hFont = font.ToHfont()
  79.            hdc = NativeMethods.CreateCompatibleDC(IntPtr.Zero)
  80.            oldObj = NativeMethods.SelectObject(hdc, hFont)
  81.            win32Err = Marshal.GetLastWin32Error()
  82.            If oldObj = IntPtr.Zero OrElse oldObj = DevCase.Win32.Common.Constants.HGDI_ERROR Then
  83.                Throw New Win32Exception(win32Err)
  84.            End If
  85.  
  86.            Dim chCode As UInteger = CUInt(Convert.ToInt32(ch))
  87.            If matrix.Equals(New GlyphOutlineMatrix2()) Then
  88.                matrix = GlyphOutlineMatrix2.GetIdentityMatrix()
  89.            End If
  90.  
  91.            Dim needed As UInteger = NativeMethods.GetGlyphOutline(hdc, chCode, format, Nothing, Nothing, Nothing, matrix)
  92.  
  93.            win32Err = Marshal.GetLastWin32Error()
  94.  
  95.            Select Case needed
  96.                Case 0UI
  97.                    ' Zero curve data points were returned, meaning the glyph is empty.
  98.                    Return Nothing
  99.  
  100.                Case DevCase.Win32.Common.Constants.GDI_ERROR
  101.                    If win32Err = Win32ErrorCode.ERROR_SUCCESS Then
  102.                        ' The function returned GDI_ERROR, but no error recorded by GetLastError, meaning the function succeeded.
  103.                        ' Tests carried out have shown that when this happens the glyph simply does not exists.
  104.                        Return Nothing
  105.                    Else
  106.                        Throw New Win32Exception(win32Err)
  107.                    End If
  108.  
  109.                Case Else
  110.                    Dim bufferPtr As IntPtr = Marshal.AllocHGlobal(New IntPtr(needed))
  111.                    Try
  112.                        Dim got As UInteger = NativeMethods.GetGlyphOutline(hdc, chCode, format, Nothing, needed, bufferPtr, matrix)
  113.                        win32Err = Marshal.GetLastWin32Error()
  114.                        If got = DevCase.Win32.Common.Constants.GDI_ERROR AndAlso
  115.                           win32Err <> Win32ErrorCode.ERROR_SUCCESS Then
  116.                            Throw New Win32Exception(win32Err)
  117.                        End If
  118.  
  119.                        Dim result(CInt(got) - 1) As Byte
  120.                        Marshal.Copy(bufferPtr, result, 0, CInt(got))
  121.                        Return result
  122.                    Finally
  123.                        Marshal.FreeHGlobal(bufferPtr)
  124.                    End Try
  125.  
  126.            End Select
  127.  
  128.        Finally
  129.            If hFont <> IntPtr.Zero Then
  130.                NativeMethods.DeleteObject(hFont)
  131.            End If
  132.            If oldObj <> IntPtr.Zero Then
  133.                NativeMethods.DeleteObject(oldObj)
  134.            End If
  135.            If hdc <> IntPtr.Zero Then
  136.                NativeMethods.DeleteDC(hdc)
  137.            End If
  138.  
  139.        End Try
  140.  
  141.    End Function
  142.  
  143.    ''' <summary>
  144.    ''' Determines whether the glyph outline for the specified character in the source <see cref="System.Drawing.Font"/>
  145.    ''' is identical to the glyph outline of the same character in another <see cref="System.Drawing.Font"/>.
  146.    ''' </summary>
  147.    '''
  148.    ''' <param name="firstFont">
  149.    ''' The first <see cref="System.Drawing.Font"/> to compare.
  150.    ''' </param>
  151.    '''
  152.    ''' <param name="secondFont">
  153.    ''' The second <see cref="System.Drawing.Font"/> to compare.
  154.    ''' </param>
  155.    '''
  156.    ''' <param name="ch">
  157.    ''' The character whose glyph outline will be compared between the two fonts.
  158.    ''' </param>
  159.    '''
  160.    ''' <returns>
  161.    ''' <see langword="True"/> if both fonts produce identical outlines for the specified glyph.
  162.    ''' <para></para>
  163.    ''' <see langword="False"/> if the outlines differ or if one of the fonts has an empty glyph.
  164.    ''' If the glyph outlines are empty in both fonts, returns <see langword="True"/>.
  165.    ''' </returns>
  166.    <Extension>
  167.    <EditorBrowsable(EditorBrowsableState.Always)>
  168.    <DebuggerStepThrough>
  169.    Public Function GlyphOutlinesAreEqual(firstFont As Font, secondFont As Font, ch As Char) As Boolean
  170.  
  171.        Dim firstBytes As Byte() = FontExtensions.GetGlyphOutlineData(firstFont, ch, GetGlyphOutlineFormat.Native)
  172.        Dim secondBytes As Byte() = FontExtensions.GetGlyphOutlineData(secondFont, ch, GetGlyphOutlineFormat.Native)
  173.  
  174.        Return (firstBytes Is Nothing AndAlso secondBytes Is Nothing) OrElse
  175.               (
  176.                 (firstBytes Is Nothing = (secondBytes Is Nothing)) AndAlso
  177.                  firstBytes.SequenceEqual(secondBytes)
  178.               )
  179.    End Function
  180.  
  181.    ''' <summary>
  182.    ''' Computes a similarity score between the glyph outline for the
  183.    ''' specified character in the source <see cref="System.Drawing.Font"/>,
  184.    ''' and the the glyph outline of the same character in another <see cref="System.Drawing.Font"/>.
  185.    ''' </summary>
  186.    '''
  187.    ''' <param name="firstFont">
  188.    ''' The first <see cref="System.Drawing.Font"/> to compare.
  189.    ''' </param>
  190.    '''
  191.    ''' <param name="secondFont">
  192.    ''' The second <see cref="System.Drawing.Font"/> to compare.
  193.    ''' </param>
  194.    '''
  195.    ''' <param name="ch">
  196.    ''' The character whose glyph outlines will be compared between the two fonts.
  197.    ''' </param>
  198.    '''
  199.    ''' <returns>
  200.    ''' A <see cref="Single"/> value between 0.0 and 1.0 representing the similarity
  201.    ''' (the number of matching bytes in the outline data) of the glyph outlines.
  202.    ''' <para></para>
  203.    ''' If one of the fonts has an empty glyph, returns 0. If the glyph outlines are empty in both fonts, returns 1.
  204.    ''' </returns>
  205.    <Extension>
  206.    <EditorBrowsable(EditorBrowsableState.Always)>
  207.    <DebuggerStepThrough>
  208.    Public Function GetGlyphOutlineSimilarity(firstFont As Font, secondFont As Font, ch As Char) As Single
  209.  
  210.        Dim firstBytes As Byte() = FontExtensions.GetGlyphOutlineData(firstFont, ch, GetGlyphOutlineFormat.Native)
  211.        Dim secondBytes As Byte() = FontExtensions.GetGlyphOutlineData(secondFont, ch, GetGlyphOutlineFormat.Native)
  212.  
  213.        If firstBytes Is Nothing AndAlso secondBytes Is Nothing Then
  214.            Return 1.0F
  215.        End If
  216.  
  217.        If (firstBytes Is Nothing) <> (secondBytes Is Nothing) Then
  218.            Return 0.0F
  219.        End If
  220.  
  221.        Dim maxLength As Integer = System.Math.Max(firstBytes.Length, secondBytes.Length)
  222.        Dim minLength As Integer = System.Math.Min(firstBytes.Length, secondBytes.Length)
  223.        Dim equalCount As Integer = 0
  224.  
  225.        For i As Integer = 0 To minLength - 1
  226.            If firstBytes(i) = secondBytes(i) Then
  227.                equalCount += 1
  228.            End If
  229.        Next
  230.  
  231.        Return CSng(equalCount) / maxLength
  232.    End Function
  233.  
  234. End Module
5  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets) en: 2 Septiembre 2025, 10:12 am
Métodos universales para trabajar (otros) aspectos básicos con fuentes de texto (.ttf y .otf)...

(AL FINAL DE ESTE POST HE COMPARTIDO UN EJEMPLO DE USO 😏)

Funciones 'UtilFonts.FontHasGlyph', 'UtilFonts.FontHasGlyphs', 'FontExtensions.HasGlyph' y 'FontExtensions.HasGlyphs'

    Sirven para determinar si existen glifos en una fuente de texto para un caracter o una serie de caracteres específicos.

    Se utilizaría, por ejemplo, con este tipo de fuente que no tiene glifos propios para las vocales con tilde:

   

Funciones 'UtilFonts.FontGlyphHasOutline' y 'FontExtensions.GlyphHasOutline'

    Sirven para determinar si un glifo está vacío (no hay contornos dibujados).

    Se utilizaría, por ejemplo, con este tipo de fuentes que no dibujan las vocales con tilde:

   

    Tener en cuenta que esta función solo sirve para determinar si el glifo contiene algo,
    no puede determinar si el glifo es una figura incompleta como por ejemplo la de esta vocal que solo tiene la tilde:

   



El código fuente

Imports necesarios

Código
  1. Imports System.ComponentModel
  2. Imports System.Drawing
  3. Imports System.Drawing.Text
  4. Imports System.IO
  5. Imports System.Runtime.CompilerServices
  6. Imports System.Runtime.InteropServices
  7.  
  8. Imports DevCase.Win32
  9. Imports DevCase.Win32.Enums
  10. Imports DevCase.Win32.Structures

Clases secundarias requeridas

(Lo siento pero he tenido que borrar mucha documentación XML -no esencial- para que me quepa todo el código en este post.)

Código
  1. #Region " Constants "
  2.  
  3. Namespace DevCase.Win32.Common.Constants
  4.  
  5.    <HideModuleName>
  6.    Friend Module Constants
  7.  
  8. #Region " GDI32 "
  9.  
  10.    ''' <summary>
  11.    ''' Error return value for some GDI32 functions.
  12.    ''' </summary>
  13.    Public Const GDI_ERROR As UInteger = &HFFFFFFFFUI
  14.  
  15.    ''' <summary>
  16.    ''' Error return value for some GDI32 functions.
  17.    ''' </summary>
  18.    Public ReadOnly HGDI_ERROR As New IntPtr(-1)
  19.  
  20. #End Region
  21.  
  22.    End Module
  23.  
  24. End Namespace
  25.  
  26. #End Region

Código
  1. #Region " Enums "
  2.  
  3. Namespace DevCase.Win32.Enums
  4.  
  5.    ''' <remarks>
  6.    ''' List of System Error Codes: <see href="https://docs.microsoft.com/en-us/windows/desktop/Debug/system-error-codes"/>.
  7.    ''' </remarks>
  8.    Public Enum Win32ErrorCode As Integer
  9.  
  10.        ''' <summary>
  11.        ''' The operation completed successfully.
  12.        ''' </summary>
  13.        ERROR_SUCCESS = &H0
  14.    End Enum
  15.  
  16.    ''' <remarks>
  17.    ''' <see href="https://learn.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-wcrange"/>
  18.    ''' </remarks>
  19.    <Flags>
  20.    Public Enum GetGlyphIndicesFlags ' GGI
  21.  
  22.        ''' <summary>
  23.        ''' Marks unsupported glyphs with the hexadecimal value 0xFFFF.
  24.        ''' </summary>
  25.        MarkNonExistingGlyphs = 1 ' GGI_MARK_NONEXISTING_GLYPHS
  26.    End Enum
  27.  
  28.    ''' <remarks>
  29.    ''' <see href="https://learn.microsoft.com/en-us/windows/win32/api/wingdi/nf-wingdi-getglyphoutlinew"/>
  30.    ''' </remarks>
  31.    Public Enum GetGlyphOutlineFormat ' GGO
  32.        Metrics = 0
  33.        Bitmap = 1
  34.  
  35.        ''' <summary>
  36.        ''' The function retrieves the curve data points in the rasterizer's native format and uses the font's design units.
  37.        ''' </summary>
  38.        Native = 2
  39.  
  40.        Bezier = 3
  41.        BitmapGray2 = 4
  42.        BitmapGray4 = 5
  43.        BitmapGray8 = 6
  44.        GlyphIndex = &H80
  45.        Unhinted = &H100
  46.    End Enum
  47.  
  48. End Namespace
  49.  
  50. #End Region

Código
  1. #Region " Structures "
  2.  
  3.    Namespace DevCase.Win32.Structures
  4.  
  5.    #Region " GlyphMetrics "
  6.  
  7.        ''' <remarks>
  8.        ''' <see href="https://learn.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-glyphmetrics"/>
  9.        ''' </remarks>
  10.        <StructLayout(LayoutKind.Sequential)>
  11.        Public Structure GlyphMetrics
  12.            Public BlackBoxX As UInteger
  13.            Public BlackBoxY As UInteger
  14.            Public GlyphOrigin As NativePoint
  15.            Public CellIncX As Short
  16.            Public CellIncY As Short
  17.        End Structure
  18.  
  19.    #End Region
  20.  
  21.    #Region " NativePoint (POINT) "
  22.  
  23.    ''' <summary>
  24.    ''' Defines the x- and y- coordinates of a point.
  25.    ''' </summary>
  26.    '''
  27.    ''' <remarks>
  28.    ''' <see href="https://msdn.microsoft.com/en-us/library/windows/desktop/dd162805%28v=vs.85%29.aspx"/>
  29.    ''' </remarks>
  30.    <DebuggerStepThrough>
  31.    <StructLayout(LayoutKind.Sequential)>
  32.    Public Structure NativePoint
  33.  
  34. #Region " Fields "
  35.  
  36.        Public X As Integer
  37.        Public Y As Integer
  38.  
  39. #End Region
  40.  
  41. #Region " Constructors "
  42.  
  43.        Public Sub New(x As Integer, y As Integer)
  44.            Me.X = x
  45.            Me.Y = y
  46.        End Sub
  47.  
  48.        Public Sub New(pt As Point)
  49.            Me.New(pt.X, pt.Y)
  50.        End Sub
  51.  
  52. #End Region
  53.  
  54. #Region " Operator Conversions "
  55.  
  56.        Public Shared Widening Operator CType(pt As NativePoint) As Point
  57.            Return New Point(pt.X, pt.Y)
  58.        End Operator
  59.  
  60.        Public Shared Widening Operator CType(pt As Point) As NativePoint
  61.            Return New NativePoint(pt.X, pt.Y)
  62.        End Operator
  63.  
  64. #End Region
  65.  
  66.    End Structure
  67.  
  68.    #End Region
  69.  
  70.    #Region " GlyphOutlineMatrix2 "
  71.  
  72.    ''' <remarks>
  73.    ''' <see href="https://learn.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-mat2"/>
  74.    ''' </remarks>
  75.    <StructLayout(LayoutKind.Sequential)>
  76.    Public Structure GlyphOutlineMatrix2 ' MAT2
  77.  
  78.        Public M11 As Fixed
  79.        Public M12 As Fixed
  80.        Public M21 As Fixed
  81.        Public M22 As Fixed
  82.  
  83.        ''' <summary>
  84.        ''' Gets an <see cref="GlyphOutlineMatrix2"/> transformation in which the transformed graphical object is identical to the source object.
  85.        ''' This is called an identity matrix.
  86.        ''' <para></para>
  87.        ''' In this identity matrix,
  88.        ''' the value of <see cref="GlyphOutlineMatrix2.M11"/> is 1,
  89.        ''' the value of <see cref="GlyphOutlineMatrix2.M12"/> is zero,
  90.        ''' the value of <see cref="GlyphOutlineMatrix2.M21"/> is zero,
  91.        ''' and the value of <see cref="GlyphOutlineMatrix2.M22"/> is 1.
  92.        ''' </summary>
  93.        '''
  94.        ''' <returns>
  95.        ''' The resulting <see cref="GlyphOutlineMatrix2"/>.
  96.        ''' </returns>
  97.        Public Shared Function GetIdentityMatrix() As GlyphOutlineMatrix2
  98.            Return New GlyphOutlineMatrix2() With {
  99.            .M11 = New Fixed With {.Value = 1},
  100.            .M22 = New Fixed With {.Value = 1}
  101.        }
  102.        End Function
  103.  
  104.    End Structure
  105.  
  106.    #End Region
  107.  
  108.    #Region " Fixed "
  109.  
  110.    ''' <summary>
  111.    ''' Contains the integral and fractional parts of a fixed-point real number.
  112.    ''' <para></para>
  113.    ''' Note: The <see cref="Fixed"/> structure is used to describe the elements of the <see cref="GlyphOutlineMatrix2"/> structure.
  114.    ''' </summary>
  115.    '''
  116.    ''' <remarks>
  117.    ''' <see href="https://docs.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-fixed"/>
  118.    ''' </remarks>
  119.    <StructLayout(LayoutKind.Sequential)>
  120.    Public Structure Fixed
  121.  
  122. #Region " Public Fields "
  123.  
  124.        ''' <summary>
  125.        ''' The fractional value.
  126.        ''' </summary>
  127.        Public Fraction As UShort
  128.  
  129.        ''' <summary>
  130.        ''' The integral value.
  131.        ''' </summary>
  132.        Public Value As Short
  133.  
  134. #End Region
  135.  
  136. #Region " Operator Conversions "
  137.  
  138.        Public Shared Widening Operator CType(f As Fixed) As Decimal
  139.  
  140.            Return Decimal.Parse($"{f.Value.ToString(NumberFormatInfo.InvariantInfo)}{NumberFormatInfo.InvariantInfo.NumberDecimalSeparator}{f.Fraction.ToString(NumberFormatInfo.InvariantInfo)}", NumberFormatInfo.InvariantInfo)
  141.        End Operator
  142.  
  143.        Public Shared Widening Operator CType(dec As Decimal) As Fixed
  144.  
  145.            Return New Fixed With {
  146.                .Value = CShort(System.Math.Truncate(System.Math.Truncate(dec))),
  147.                .Fraction = UShort.Parse(dec.ToString(NumberFormatInfo.InvariantInfo).Split({NumberFormatInfo.InvariantInfo.NumberDecimalSeparator}, StringSplitOptions.None)(1), NumberFormatInfo.InvariantInfo)
  148.            }
  149.        End Operator
  150.  
  151. #End Region
  152.  
  153. #Region " Public Methods "
  154.  
  155.        Public Overrides Function ToString() As String
  156.  
  157.            Return CDec(Me).ToString()
  158.        End Function
  159.  
  160. #End Region
  161.  
  162.    End Structure
  163.  
  164.    #End Region
  165.  
  166.    End Namespace
  167.  
  168. #End Region
  169.  

Código
  1. #Region " NativeMethods "
  2.  
  3. Namespace DevCase.Win32.NativeMethods
  4.  
  5.    <SuppressUnmanagedCodeSecurity>
  6.    Friend Module Gdi32
  7.  
  8.        ''' <summary>
  9.        ''' Creates a memory device context (DC) compatible with the specified device.
  10.        ''' </summary>
  11.        '''
  12.        ''' <remarks>
  13.        ''' <see href="https://msdn.microsoft.com/en-us/library/windows/desktop/dd183489%28v=vs.85%29.aspx"/>
  14.        ''' </remarks>
  15.        <DllImport("gdi32.dll", SetLastError:=True)>
  16.        Public Function CreateCompatibleDC(hdc As IntPtr
  17.        ) As IntPtr
  18.        End Function
  19.  
  20.        ''' <summary>
  21.        ''' Deletes the specified device context (DC).
  22.        ''' <para></para>
  23.        ''' An application must not delete a DC whose handle was obtained by calling the <see cref="GetDC"/> function.
  24.        ''' instead, it must call the <see cref="ReleaseDC"/> function to free the DC.
  25.        ''' </summary>
  26.        '''
  27.        ''' <remarks>
  28.        ''' <see href="https://msdn.microsoft.com/en-us/library/windows/desktop/dd183533%28v=vs.85%29.aspx"/>
  29.        ''' </remarks>
  30.        <DllImport("gdi32.dll")>
  31.        Public Function DeleteDC(hdc As IntPtr
  32.        ) As <MarshalAs(UnmanagedType.Bool)> Boolean
  33.        End Function
  34.  
  35.        ''' <summary>
  36.        ''' Selects an object into a specified device context.
  37.        ''' <para></para>
  38.        ''' The new object replaces the previous object of the same type.
  39.        ''' </summary>
  40.        '''
  41.        ''' <remarks>
  42.        ''' <see href="https://msdn.microsoft.com/en-us/library/windows/desktop/dd162957%28v=vs.85%29.aspx"/>
  43.        ''' </remarks>
  44.        <DllImport("gdi32.dll", ExactSpelling:=False)>
  45.        Public Function SelectObject(hdc As IntPtr,
  46.                                     hObject As IntPtr
  47.        ) As IntPtr
  48.        End Function
  49.  
  50.        ''' <summary>
  51.        ''' Deletes a logical pen, brush, font, bitmap, region, or palette,
  52.        ''' freeing all system resources associated with the object.
  53.        ''' <para></para>
  54.        ''' After the object is deleted, the specified handle is no longer valid.
  55.        ''' <para></para>
  56.        ''' Do not delete a drawing object (pen or brush) while it is still selected into a DC.
  57.        ''' <para></para>
  58.        ''' When a pattern brush is deleted, the bitmap associated with the brush is not deleted.
  59.        ''' The bitmap must be deleted independently.
  60.        ''' </summary>
  61.        '''
  62.        ''' <remarks>
  63.        ''' <see href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms633540%28v=vs.85%29.aspx"/>
  64.        ''' </remarks>
  65.        <DllImport("gdi32.dll", ExactSpelling:=False, SetLastError:=True)>
  66.        Public Function DeleteObject(hObject As IntPtr
  67.        ) As <MarshalAs(UnmanagedType.Bool)> Boolean
  68.        End Function
  69.  
  70.        ''' <summary>
  71.        ''' Translates a string into an array of glyph indices.
  72.        ''' <para></para>
  73.        ''' The function can be used to determine whether a glyph exists in a font.
  74.        ''' </summary>
  75.        '''
  76.        ''' <remarks>
  77.        ''' <see href="https://learn.microsoft.com/en-us/windows/win32/api/wingdi/nf-wingdi-getglyphindicesw"/>
  78.        ''' </remarks>
  79.        <DllImport("gdi32.dll", SetLastError:=False, CharSet:=CharSet.Auto, BestFitMapping:=False, ThrowOnUnmappableChar:=True)>
  80.        Public Function GetGlyphIndices(hdc As IntPtr,
  81.                                        str As String,
  82.                                        strLen As Integer,
  83.                                        <[Out], MarshalAs(UnmanagedType.LPArray, SizeParamIndex:=2)>
  84.                                        glyphIndices As UShort(),
  85.                               Optional flags As GetGlyphIndicesFlags = GetGlyphIndicesFlags.MarkNonExistingGlyphs
  86.        ) As UInteger
  87.        End Function
  88.  
  89.        ''' <summary>
  90.        ''' Retrieves the outline or bitmap for a character in the TrueType font that is selected into the specified device context.
  91.        ''' </summary>
  92.        '''
  93.        ''' <remarks>
  94.        ''' <see href="https://learn.microsoft.com/en-us/windows/win32/api/wingdi/nf-wingdi-getglyphoutlinew"/>
  95.        ''' </remarks>
  96.        <DllImport("gdi32.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
  97.        Public Function GetGlyphOutline(hdc As IntPtr,
  98.                                        ch As UInteger,
  99.                                        format As GetGlyphOutlineFormat,
  100.                            <Out> ByRef refMetrics As GlyphMetrics,
  101.                                        bufferSize As UInteger,
  102.                                        buffer As IntPtr,
  103.                                  ByRef refMatrix2 As GlyphOutlineMatrix2
  104.        ) As UInteger
  105.        End Function
  106.  
  107.    End Module
  108.  
  109. End Namespace
  110.  
  111. #End Region

Clase principal 'UtilFonts' y modulo 'FontExtensions', que contienen los métodos universales en torno a fuentes de texto

Código
  1. Public Class UtilFonts
  2.  
  3.    ''' <summary>
  4.    ''' Prevents a default instance of the <see cref="UtilFonts"/> class from being created.
  5.    ''' </summary>
  6.    Private Sub New()
  7.    End Sub
  8.  
  9.    ''' <summary>
  10.    ''' Determines whether a glyph exists in the given font file
  11.    ''' for the specified character.
  12.    ''' </summary>
  13.    '''
  14.    ''' <param name="fontFile">
  15.    ''' Path to the font file used to check for glyph availability.
  16.    ''' </param>
  17.    '''
  18.    ''' <param name="ch">
  19.    ''' The character that represents the glyph to check.
  20.    ''' </param>
  21.    '''
  22.    ''' <returns>
  23.    ''' <see langword="True"/> if a glyph exists in the font for the specified character;
  24.    ''' otherwise, <see langword="False"/>.
  25.    ''' </returns>
  26.    <DebuggerStepThrough>
  27.    Public Shared Function FontHasGlyph(fontFile As String, ch As Char) As Boolean
  28.  
  29.        Return UtilFonts.FontHasGlyphs(fontFile, ch) = 1
  30.    End Function
  31.  
  32.    ''' <summary>
  33.    ''' Determines whether a glyph exists in the given font file
  34.    ''' for all the characters in the speciied string.
  35.    ''' </summary>
  36.    '''
  37.    ''' <param name="fontFile">
  38.    ''' Path to the font file used to check for glyphs availability.
  39.    ''' </param>
  40.    '''
  41.    ''' <param name="str">
  42.    ''' A <see cref="String"/> with the character(s) that represents the glyphs to check.
  43.    ''' <para></para>
  44.    ''' Each character (or surrogate pair) is checked for a existing glyph in the font.
  45.    ''' </param>
  46.    '''
  47.    ''' <returns>
  48.    ''' The count of characters from <paramref name="str"/> parameter that have a existing glyph in the font.
  49.    ''' <para></para>
  50.    ''' A count less than the length of <paramref name="str"/> indicates that the font does not have a existing glyph for one or more characters.
  51.    ''' </returns>
  52.    '''
  53.    ''' <exception cref="FileNotFoundException">
  54.    ''' Thrown when the font file is not found.
  55.    ''' </exception>
  56.    <DebuggerStepThrough>
  57.    Public Shared Function FontHasGlyphs(fontFile As String, str As String) As UInteger
  58.  
  59.        If Not System.IO.File.Exists(fontFile) Then
  60.            Throw New FileNotFoundException("Font file not found.", fileName:=fontFile)
  61.        End If
  62.  
  63.        Using pfc As New PrivateFontCollection()
  64.            pfc.AddFontFile(fontFile)
  65.  
  66.            Using f As New Font(pfc.Families(0), emSize:=1)
  67.                Return FontExtensions.HasGlyphs(f, str)
  68.            End Using
  69.        End Using
  70.    End Function
  71.  
  72.    ''' <summary>
  73.    ''' Determines whether a glyph for the specified character in the given font file has an outline.
  74.    ''' <para></para>
  75.    ''' This is useful to determine whether the glyph is empty (no character is drawn),
  76.    ''' but note that a glyph with outlines does not necessarily mean that the character is fully represented.
  77.    ''' Some fonts, for instance, only renders diacritical marks for accented vowels
  78.    ''' instead the full letter (e.g., "<b>´</b>" instead of "<b>í</b>").
  79.    ''' This function solely determines whether the glyph draws an outline, nothing more.
  80.    ''' <para></para>
  81.    ''' To determine whether a glyph exists in the given font file for the specified character, use
  82.    ''' <see cref="UtilFonts.FontHasGlyph"/> or <see cref="UtilFonts.FontHasGlyphs"/> instead.
  83.    ''' </summary>
  84.    '''
  85.    ''' <param name="fontFile">
  86.    ''' Path to the font file used to check for glyph availability.
  87.    ''' </param>
  88.    '''
  89.    ''' <param name="ch">
  90.    ''' The character that represents the glyph to check in the font.
  91.    ''' </param>
  92.    '''
  93.    ''' <returns>
  94.    ''' Returns <see langword="True"/> if the glyph has an outline (visible shape data exists).
  95.    ''' <para></para>
  96.    ''' Returns <see langword="False"/> if the glyph does not have an outline,
  97.    ''' meaning the glyph is empty/unsupported by the font.
  98.    ''' </returns>
  99.    '''
  100.    ''' <exception cref="FileNotFoundException">
  101.    ''' Thrown when the font file is not found.
  102.    ''' </exception>
  103.    <DebuggerStepThrough>
  104.    Public Shared Function FontGlyphHasOutline(fontFile As String, ch As Char) As Boolean
  105.  
  106.        If Not System.IO.File.Exists(fontFile) Then
  107.            Throw New FileNotFoundException("Font file not found.", fileName:=fontFile)
  108.        End If
  109.  
  110.        Using pfc As New PrivateFontCollection()
  111.            pfc.AddFontFile(fontFile)
  112.  
  113.            Using f As New Font(pfc.Families(0), emSize:=1)
  114.                Return FontExtensions.GlyphHasOutline(f, ch)
  115.            End Using
  116.        End Using
  117.    End Function
  118.  
  119. End Class

Código
  1. Module FontExtensions
  2.  
  3.    ''' <summary>
  4.    ''' Determines whether a glyph exists in the given <see cref="System.Drawing.Font"/>
  5.    ''' for the specified character.
  6.    ''' </summary>
  7.    '''
  8.    ''' <param name="font">
  9.    ''' The <see cref="System.Drawing.Font"/> used to check for glyph availability.
  10.    ''' </param>
  11.    '''
  12.    ''' <param name="ch">
  13.    ''' The character that represents the glyph to check.
  14.    ''' </param>
  15.    '''
  16.    ''' <returns>
  17.    ''' <see langword="True"/> if a glyph exists in the font for the specified character;
  18.    ''' otherwise, <see langword="False"/>.
  19.    ''' </returns>
  20.    <Extension>
  21.    <EditorBrowsable(EditorBrowsableState.Always)>
  22.    <DebuggerStepThrough>
  23.    Public Function HasGlyph(font As Font, ch As Char) As Boolean
  24.  
  25.        Return FontExtensions.HasGlyphs(font, ch) = 1
  26.    End Function
  27.  
  28.    ''' <summary>
  29.    ''' Determines whether a glyph exists in the given <see cref="System.Drawing.Font"/>
  30.    ''' for all the characters in the speciied string.
  31.    ''' </summary>
  32.    '''
  33.    ''' <param name="font">
  34.    ''' The <see cref="System.Drawing.Font"/> used to check for glyphs availability.
  35.    ''' </param>
  36.    '''
  37.    ''' <param name="str">
  38.    ''' A <see cref="String"/> with the character(s) that represents the glyphs to check.
  39.    ''' <para></para>
  40.    ''' Each character (or surrogate pair) is checked for a existing glyph in the font.
  41.    ''' </param>
  42.    '''
  43.    ''' <returns>
  44.    ''' The count of characters from <paramref name="str"/> parameter that have a existing glyph in the font.
  45.    ''' <para></para>
  46.    ''' A count less than the length of <paramref name="str"/> indicates that the font does not have a existing glyph for one or more characters.
  47.    ''' </returns>
  48.    '''
  49.    ''' <exception cref="ArgumentNullException">
  50.    ''' Thrown when <paramref name="font"/> or <paramref name="str"/> are null.
  51.    ''' </exception>
  52.    '''
  53.    ''' <exception cref="Win32Exception">
  54.    ''' Thrown when a call to Windows API GDI32 functions (creating device context, selecting font, or retrieving glyph indices) fails.
  55.    ''' </exception>
  56.    <Extension>
  57.    <EditorBrowsable(EditorBrowsableState.Always)>
  58.    <DebuggerStepThrough>
  59.    Public Function HasGlyphs(font As Font, str As String) As UInteger
  60.  
  61.        If font Is Nothing Then
  62.            Throw New ArgumentNullException(paramName:=NameOf(font))
  63.        End If
  64.  
  65.        If String.IsNullOrEmpty(str) Then
  66.            Throw New ArgumentNullException(paramName:=NameOf(str))
  67.        End If
  68.  
  69.        Dim hdc As IntPtr
  70.        Dim hFont As IntPtr
  71.        Dim oldObj As IntPtr
  72.  
  73.        Dim win32Err As Integer
  74.  
  75.        Try
  76.            hFont = font.ToHfont()
  77.            hdc = NativeMethods.CreateCompatibleDC(IntPtr.Zero)
  78.            win32Err = Marshal.GetLastWin32Error()
  79.            If hdc = IntPtr.Zero Then
  80.                Throw New Win32Exception(win32Err)
  81.            End If
  82.  
  83.            oldObj = NativeMethods.SelectObject(hdc, hFont)
  84.            win32Err = Marshal.GetLastWin32Error()
  85.            If oldObj = IntPtr.Zero OrElse oldObj = DevCase.Win32.Common.Constants.HGDI_ERROR Then
  86.                Throw New Win32Exception(win32Err)
  87.            End If
  88.  
  89.            ' Reserve output for each text unit (can be 1 or 2 chars if it's a surrogate pair).
  90.            Dim strLen As Integer = str.Length
  91.            Dim indices As UShort() = New UShort(strLen - 1) {}
  92.            ' Get the glyph indices for the string in the given device context.
  93.            Dim converted As UInteger = NativeMethods.GetGlyphIndices(hdc, str, strLen, indices, GetGlyphIndicesFlags.MarkNonExistingGlyphs)
  94.            win32Err = Marshal.GetLastWin32Error()
  95.            If converted = DevCase.Win32.Common.Constants.GDI_ERROR Then
  96.                Throw New Win32Exception(win32Err)
  97.            End If
  98.  
  99.            ' Count glyphs that exist (index <> 0xFFFF).
  100.            ' If any glyph index is 0xFFFF, the glyph does not exist in that font.
  101.            Dim count As UInteger
  102.            For Each index As UShort In indices
  103.                If index <> &HFFFFUS Then
  104.                    count += 1UI
  105.                End If
  106.            Next
  107.            Return count
  108.  
  109.        Finally
  110.            If oldObj <> IntPtr.Zero Then
  111.                NativeMethods.DeleteObject(oldObj)
  112.            End If
  113.            If hFont <> IntPtr.Zero Then
  114.                NativeMethods.DeleteObject(hFont)
  115.            End If
  116.            If hdc <> IntPtr.Zero Then
  117.                NativeMethods.DeleteDC(hdc)
  118.            End If
  119.  
  120.        End Try
  121.    End Function
  122.  
  123.  
  124.    ''' <summary>
  125.    ''' Determines whether a glyph for the specified character in the given <see cref="System.Drawing.Font"/> has an outline.
  126.    ''' <para></para>
  127.    ''' This is useful to determine whether the glyph is empty (no character is drawn),
  128.    ''' but note that a glyph with outlines does not necessarily mean that the character is fully represented.
  129.    ''' Some fonts, for instance, only renders diacritical marks for accented vowels
  130.    ''' instead the full letter (e.g., "<b>´</b>" instead of "<b>í</b>").
  131.    ''' This function solely determines whether the glyph draws an outline, nothing more.
  132.    ''' <para></para>
  133.    ''' To determine whether a glyph exists in the given font file for the specified character, use
  134.    ''' <see cref="FontExtensions.HasGlyph"/> or <see cref="FontExtensions.HasGlyphs"/> instead.
  135.    ''' </summary>
  136.    '''
  137.    ''' <param name="font">
  138.    ''' The <see cref="System.Drawing.Font"/> used to check for glyph availability.
  139.    ''' </param>
  140.    '''
  141.    ''' <param name="ch">
  142.    ''' The character that represents the glyph to check in the font.
  143.    ''' </param>
  144.    '''
  145.    ''' <returns>
  146.    ''' Returns <see langword="True"/> if the glyph has an outline (visible shape data exists).
  147.    ''' <para></para>
  148.    ''' Returns <see langword="False"/> if the glyph does not have an outline,
  149.    ''' meaning the glyph is empty/unsupported by the font.
  150.    ''' </returns>
  151.    <Extension>
  152.    <EditorBrowsable(EditorBrowsableState.Always)>
  153.    <DebuggerStepThrough>
  154.    Public Function GlyphHasOutline(font As Font, ch As Char) As Boolean
  155.  
  156.        If font Is Nothing Then
  157.            Throw New ArgumentNullException(paramName:=NameOf(font))
  158.        End If
  159.  
  160.        Dim hdc As IntPtr
  161.        Dim hFont As IntPtr
  162.        Dim oldObj As IntPtr
  163.  
  164.        Dim win32Err As Integer
  165.  
  166.        Try
  167.            hFont = font.ToHfont()
  168.            hdc = NativeMethods.CreateCompatibleDC(IntPtr.Zero)
  169.            oldObj = NativeMethods.SelectObject(hdc, hFont)
  170.            win32Err = Marshal.GetLastWin32Error()
  171.            If oldObj = IntPtr.Zero OrElse oldObj = DevCase.Win32.Common.Constants.HGDI_ERROR Then
  172.                Throw New Win32Exception(win32Err)
  173.            End If
  174.  
  175.            Dim chCode As UInteger = CUInt(Convert.ToInt32(ch))
  176.            Dim format As GetGlyphOutlineFormat = GetGlyphOutlineFormat.Native
  177.            Dim matrix As GlyphOutlineMatrix2 = GlyphOutlineMatrix2.GetIdentityMatrix()
  178.  
  179.            Dim ptCount As UInteger = NativeMethods.GetGlyphOutline(hdc, chCode, format, Nothing, Nothing, Nothing, matrix)
  180.            win32Err = Marshal.GetLastWin32Error()
  181.            Select Case ptCount
  182.  
  183.                Case 0UI
  184.                    ' Zero curve data points were returned, meaning the glyph is empty/invisible.
  185.                    Return False
  186.  
  187.                Case DevCase.Win32.Common.Constants.GDI_ERROR
  188.                    If win32Err = Win32ErrorCode.ERROR_SUCCESS Then
  189.                        ' The function returned GDI_ERROR, but no error recorded by GetLastError, meaning the function succeeded.
  190.                        ' Tests carried out have shown that when this happens the glyph simply does not exists.
  191.                        Return False
  192.                    Else
  193.                        Throw New Win32Exception(win32Err)
  194.                    End If
  195.  
  196.                Case Else
  197.                    Return True
  198.  
  199.            End Select
  200.  
  201.        Finally
  202.            If oldObj <> IntPtr.Zero Then
  203.                NativeMethods.DeleteObject(oldObj)
  204.            End If
  205.            If hFont <> IntPtr.Zero Then
  206.                NativeMethods.DeleteObject(hFont)
  207.            End If
  208.            If hdc <> IntPtr.Zero Then
  209.                NativeMethods.DeleteDC(hdc)
  210.            End If
  211.  
  212.        End Try
  213.  
  214.        ' ===================================================
  215.        '   ALTERNATIVE METHODOLOGY USING PURE MANAGED GDI+
  216.        '
  217.        ' (results are the same than using Windows API calls)
  218.        ' ===================================================
  219.        '
  220.        '
  221.        'If font Is Nothing Then
  222.        '    Throw New ArgumentNullException(paramName:=NameOf(font))
  223.        'End If
  224.        '
  225.        'If font.Unit = GraphicsUnit.Pixel AndAlso font.Size < 8 Then
  226.        '    Dim msg As String =
  227.        '        "Font size must be equals or greater than 8 pixels when using GraphicsUnit.Pixel to avoid unreliable pixel detection. " &
  228.        '        "Suggested font size is 16 pixel size; A value of 32, 64 or bigger pixel size would produce the same results."
  229.        '    Throw New ArgumentException(msg)
  230.        '
  231.        'ElseIf font.Size < 4 Then
  232.        '    Dim msg As String =
  233.        '        "Font size must be equals or greater than 4 to avoid unreliable pixel detection. " &
  234.        '        "Suggested usage is GraphicsUnit.Pixel with a font size of 16 pixels; " &
  235.        '        "A value of 32, 64 or bigger pixel size would produce the same results."
  236.        '    Throw New ArgumentException(msg)
  237.        '
  238.        'End If
  239.        '
  240.        '' Measure the required size for the glyph.
  241.        'Dim requiredSize As Size
  242.        'Using tempBmp As New Bitmap(1, 1)
  243.        '    Using g As Graphics = Graphics.FromImage(tempBmp)
  244.        '        Dim sizeF As SizeF = g.MeasureString(ch, font)
  245.        '        ' Add a small margin to avoid clipping due to rounding.
  246.        '        requiredSize = New Size(CInt(System.Math.Ceiling(sizeF.Width)) + 4,
  247.        '                                CInt(System.Math.Ceiling(sizeF.Height)) + 4)
  248.        '    End Using
  249.        'End Using
  250.        '
  251.        '' Create a bitmap big enough to render the glyph,
  252.        '' filling the bitmap background with white color and
  253.        '' drawing the character in black.
  254.        'Using bmp As New Bitmap(requiredSize.Width, requiredSize.Height),
  255.        '      g As Graphics = Graphics.FromImage(bmp)
  256.        '    ' Using AntiAlias may help ensure that very thin glyph strokes
  257.        '    ' still produce detectable pixels, with gray edges.
  258.        '    ' Without anti-aliasing, such strokes might render too faint or disappear entirely,
  259.        '    ' causing the glyph to be misidentified as empty.
  260.        '    g.TextRenderingHint = Drawing.Text.TextRenderingHint.AntiAlias
  261.        '    g.Clear(Color.White)
  262.        '    g.DrawString(ch, font, Brushes.Black, 0, 0)
  263.        '
  264.        '    Dim rect As New Rectangle(0, 0, bmp.Width, bmp.Height)
  265.        '    Dim bmpData As BitmapData = bmp.LockBits(rect, Imaging.ImageLockMode.ReadOnly, Imaging.PixelFormat.Format32bppArgb)
  266.        '
  267.        '    Try
  268.        '        Dim ptr As IntPtr = bmpData.Scan0
  269.        '        Dim bytes As Integer = System.Math.Abs(bmpData.Stride) * bmp.Height
  270.        '        Dim pixelValues(bytes - 1) As Byte
  271.        '        Marshal.Copy(ptr, pixelValues, 0, bytes)
  272.        '
  273.        '        ' Iterate through each pixel.
  274.        '        ' PixelFormat.Format32bppArgb stores pixels as [Blue][Green][Red][Alpha]
  275.        '        ' i=Blue, i+1=Green, i+2=Red, i+3=Alpha
  276.        '        For i As Integer = 0 To pixelValues.Length - 1 Step 4
  277.        '            Dim red As Byte = pixelValues(i + 2)
  278.        '
  279.        '            ' Check if the pixel is darker than nearly-white (threshold 250)
  280.        '            ' If so, we found a visible pixel, meaning the glyph is drawn.
  281.        '            If red < 250 Then
  282.        '                Return True
  283.        '            End If
  284.        '        Next
  285.        '    Finally
  286.        '        bmp.UnlockBits(bmpData)
  287.        '
  288.        '    End Try
  289.        'End Using
  290.        '
  291.        '' No visible pixels found, meaning the glyph is empty/unsupported by the font.
  292.        'Return False
  293.  
  294.    End Function
  295.  
  296. End Module

Modo de empleo

El siguiente ejemplo verifica en los archivos de fuente .ttf de un directorio específico si la tipografía incluye los glifos correspondientes a los caracteres á, é, í, ó y ú. En caso de que falte algún glifo, se imprime un mensaje en consola indicando los glifos ausentes, y finalmente envía el archivo de fuente a la papelera de reciclaje (hay que descomentar las lineas marcadas).

Código
  1. Dim fontFiles As IEnumerable(Of String) = Directory.EnumerateFiles("C:\Fonts", "*.ttf", SearchOption.TopDirectoryOnly)
  2. Dim fontsToDelete As New HashSet(Of String)()
  3. Dim chars As Char() = "áéíóú".ToCharArray()
  4.  
  5. For Each fontFile As String In fontFiles
  6.    Dim missingChars As New HashSet(Of Char)()
  7.  
  8.    For Each ch As Char In chars
  9.        If Not UtilFonts.FontHasGlyph(fontFile, ch) OrElse
  10.           Not UtilFonts.FontGlyphHasOutline(fontFile, ch) Then
  11.            missingChars.Add(ch)
  12.        End If
  13.    Next
  14.  
  15.    If missingChars.Count > 0 Then
  16.        Console.WriteLine($"[{Path.GetFileName(fontFile)}] Missing glyphs: {String.Join(", ", missingChars)}")
  17.        fontsToDelete.Add(fontFile)
  18.    End If
  19. Next
  20.  
  21. For Each fontFile As String In fontsToDelete
  22.    ' Console.WriteLine($"Deleting font file: {fontFile}")
  23.    ' Microsoft.VisualBasic.FileIO.FileSystem.DeleteFile(fontFile, FileIO.UIOption.OnlyErrorDialogs, FileIO.RecycleOption.SendToRecycleBin)
  24. Next

Por último, quiero comentar que he experimentado estas funciones de forma muy minuciosa, primero con muestras pequeñas de 2 o 3 fuentes... varias veces por cada cambio significativo realizado en el código, y después he probado la versión final con aprox. 14.000 archivos de fuentes de texto, y los resultados han sido muy satisfactorios detectando varios miles de fuentes a los que le faltan los glifos especificados, y, aunque no he podido revisar todos esos miles de fuentes una a una, no he encontrado ningún falso positivo entre varios cientos de fuentes que sí he revisado manualmente.

Eso es todo. 👋
6  Informática / Software / Re: Es posible descargar videos de Patreon? en: 1 Septiembre 2025, 12:41 pm
desde línea de comandos puedes descargarlos con yt-dlp

Hay interfaces gráficas de terceros:

https://github.com/kannagi0303/yt-dlp-gui
https://github.com/ErrorFlynn/ytdlp-interface

Atentamente,
Elektro.
7  Foros Generales / Foro Libre / Re: Viaje a la nueva Corea del Norte: ¿un paraíso turístico del comunismo? en: 31 Agosto 2025, 17:46 pm
Bueno para no desviar el tema seguimos hablando del gordi de corea del norte. :xD

Viendo la tecnología que tienen tan anticuada, que literalmente todo es una bonita fachada por fuera pero podredumbre por dentro (sería muy injusto decir que es lo mismo y tan evidente como en Myanmar, pero cierto parecido si que tiene: las apariencias engañan), yo me apostaría que sus misiles están tan vacíos como el cerebro de Kim Jong-un intentando comprender el funcionamiento de un iPhone. En serio, me viene a la cabeza un hombre de las cavernas acercando un palo al fuego por primera vez y quedándose pensativo durante varios minutos mientras se consume: "Uhmm… ¿que poder hacer yo ahora con palo de fuego?".

Y es cierto que han lanzado algunos misiles a modo de demostración, pero a ver... es que es un régimen de comunistas, no de tontos, el señor gordito –y que según las creencias del país no necesita hacer popó porque es prácticamente un dios– comprará algunos misiles en buenas condiciones para lanzarlos al mar y aparentar ser una amenaza real para el mundo, que debe ser respetada. Si no lanzasen misiles de vez en cuando para intentar intimidar, quizás ya no habría ninguna dictadura comunista en ese país ¿Me entiendes?, el país ya habría sido invadido rescatado de ese dictador, pero no por bondad de la humanidad, no por justicia ni ética, sino por intereses de unos u otros actores para poder colocar de líder/primer ministro/presidente/dictador a su lacayo más leal (como en Ucrania). En fin, el caso es que el resto de misiles... el resto deben tener más aire por dentro que una bolsa de papas Lay's. Mi opinión.

¡Un saludo!
8  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets) en: 31 Agosto 2025, 15:20 pm
Esta función pertenece a la clase 'UtilFonts' del anterior post, lo comparto aquí por que no me cabe en el otro post y por que esta función no depende de ninguna otra...

Código
  1.   ''' <summary>
  2.   ''' Retrieves the resource name of a TrueType (.ttf) or OpenType font file (.otf)
  3.   ''' by creating a temporary scalable font resource file and reading its contents.
  4.   ''' <para></para>
  5.   ''' This name may differ from the value of the following properties:
  6.   ''' <list type="bullet">
  7.   '''   <item><description><see cref="System.Drawing.Font.Name"/>.</description></item>
  8.   '''   <item><description><see cref="System.Drawing.Font.OriginalFontName"/>.</description></item>
  9.   '''   <item><description><see cref="System.Drawing.Font.SystemFontName"/>.</description></item>
  10.   '''   <item><description><see cref="System.Windows.Media.GlyphTypeface.FamilyNames"/>.</description></item>
  11.   '''   <item><description><see cref="System.Windows.Media.GlyphTypeface.Win32FamilyNames"/>.</description></item>
  12.   ''' </list>
  13.   ''' </summary>
  14.   '''
  15.   ''' <param name="fontFile">
  16.   ''' The path to the font file (e.g., <b>"C:\font.ttf"</b>).
  17.   ''' </param>
  18.   '''
  19.   ''' <returns>
  20.   ''' The resource name of the given font file.
  21.   ''' </returns>
  22.   <DebuggerStepThrough>
  23.   Public Shared Function GetFontResourceName(fontFile As String) As String
  24.  
  25.       If Not File.Exists(fontFile) Then
  26.           Dim msg As String = $"The font file does not exist: '{fontFile}'"
  27.           Throw New FileNotFoundException(msg, fontFile)
  28.       End If
  29.  
  30.       Dim fontName As String = Nothing
  31.       Dim tempFile As String = Path.Combine(Path.GetTempPath(), "~FONT.RES")
  32.  
  33.       ' Ensure any previous existing temp file is deleted.
  34.       If File.Exists(tempFile) Then
  35.           Try
  36.               File.Delete(tempFile)
  37.           Catch ex As Exception
  38.               Dim msg As String = $"Cannot delete existing temp resource file: '{tempFile}'"
  39.               Throw New IOException(msg, ex)
  40.           End Try
  41.       End If
  42.  
  43.       ' Create a temporary scalable font resource.
  44.       Dim created As Boolean = NativeMethods.CreateScalableFontResource(1UI, tempFile, fontFile, Nothing)
  45.       If Not created Then
  46.           Dim msg As String = "Failed to create scalable font resource."
  47.           Throw New IOException(msg)
  48.       End If
  49.  
  50.       Try
  51.           ' Read the temp font file resource into a string.
  52.           Dim buffer As Byte() = File.ReadAllBytes(tempFile)
  53.           Dim bufferStr As String = Encoding.Default.GetString(buffer)
  54.  
  55.           ' Look for the "FONTRES:" marker.
  56.           Const fontResMarker As String = "FONTRES:"
  57.           Dim pos As Integer = bufferStr.IndexOf(fontResMarker)
  58.           If pos < 0 Then
  59.               Dim msg As String = "FONTRES marker not found in temporary font resource file."
  60.               Throw New InvalidOperationException(msg)
  61.           End If
  62.  
  63.           pos += fontResMarker.Length
  64.           Dim endPos As Integer = bufferStr.IndexOf(ControlChars.NullChar, pos)
  65.           If endPos < 0 Then
  66.               Dim msg As String = "Cannot determine the end position of the font name string in the font resource file content."
  67.               Throw New InvalidOperationException(msg)
  68.           End If
  69.  
  70.           fontName = bufferStr.Substring(pos, endPos - pos)
  71.       Catch ex As Exception
  72.           Throw
  73.  
  74.       Finally
  75.           ' Always attempt to delete the created temporary resource file.
  76.           Try
  77.               File.Delete(tempFile)
  78.           Catch
  79.               ' Ignore deletion exceptions; cleanup best effort.
  80.           End Try
  81.  
  82.       End Try
  83.  
  84.       Return fontName
  85.   End Function
  86.  

Código
  1. #Region " NativeMethods "
  2.  
  3. Namespace DevCase.Win32.NativeMethods
  4.  
  5.    <SuppressUnmanagedCodeSecurity>
  6.    Friend Module User32
  7.  
  8. #Region " GDI32.dll "
  9.  
  10.        <DllImport("GDI32.dll", CharSet:=CharSet.Auto, SetLastError:=True, BestFitMapping:=False, ThrowOnUnmappableChar:=True)>
  11.        Friend Function CreateScalableFontResource(hidden As UInteger,
  12.                                                   resourceFile As String,
  13.                                                   fontFile As String,
  14.                                                   currentPath As String
  15.        ) As <MarshalAs(UnmanagedType.Bool)> Boolean
  16.        End Function
  17.  
  18. #End Region
  19.  
  20.    End Module
  21.  
  22. End Namespace
  23.  
  24. #End Region

OFF-TOPIC

Si alguien se pregunta: "¿Y por qué esa obsesión con las diferentes formas que puede haber para obtener el nombre de una fuente?" "¿Qué más te da un nombre u otro?" pues bueno, por que yo necesitaba hallar la forma de obtener el nombre completo amistoso exactamente tal y como se muestra en el visor de fuentes de texto de Windows (fontview.exe), por que esa es la representación más completa y la más sofisticada que he visto hasta ahora, "¿Pero por qué motivo lo necesitas exactamente?" Pues por que se me metió en la cabeza conseguirlo, y yo soy muy cabezón, sin más, así que básicamente en eso ha consistido mi investigación, con varios días de ensayo y error, junto a treinta consultas a ChatGPT con sus cien respuestas inservibles que me sacan de quicio...

En el post anterior simplemente he recopilado las diferencias que he ido encontrando al probar diversas maneras de obtener el nombre de una fuente (a lo mejor me he olvidado de alguna otra forma, no sé). A penas hay información sobre esto en Internet (sobre como obtener el nombre amistoso COMPLETO) por no decir que prácticamente no hay nada de nada; aunque bueno, una forma sé que sería leyendo las tablas en la cabecera de un archivo de fuente, pero eso es un auténtico coñazo y propenso a errores humanos, sobre todo si no eres un friki erudito... diseñador de fuentes que conoce todos los entresijos y las "variables" a tener en cuenta al analizar la cabecera de estos formatos de archivo, cosa que evidentemente yo no conozco, pero por suerte al final descubrí que la propiedad "Title" de la shell de Windows es suficiente para lograr mi propósito a la perfección, y sin tener que recurrir a experimentos tediosos que me causarían pesadillas por la noche.

Lo de instalar y desinstalar fuentes vino a continuación de lo del nombre, primero necesitaba el nombre amistoso completo, y luego ya teniendo ese nombre -fiel a la representación de Microsoft Windows- podía empezar a desarrollar ideas para hacer cosas más útiles o interesantes. Todos los códigos que he visto por Internet en diferentes lenguajes de programación para instalar un archivo de fuente se quedan muuuy cortos para mis expectativas, carecíendo de las funcionalidades más esenciales, la optimización y los controles de errores más básicos... a diferencia de lo que yo he desarrollado y compartido en el anterior post, que aunque puede que no sea perfecto (por que la perfección absoluta no existe), es mejor que todo lo que he encontrado hasta ahora, y no es por echarme flores ni parecer engreído, pero es la verdad; Me siento sorprendido al no haber descubierto ningún otro programador que haya hecho/compartido un código universal para instalar fuentes de texto de forma más o menos eficiente, confiable y versátil. Quizás lo haya, pero yo no lo encontré. Códigos cortitos y que cumplen la funcionalidad mínima de "instalar una fuente" sin importar ningún factor, de esos hay muchos en Internet, pero como digo un BUEN CÓDIGO no encontré.

Lo próximo que comparta en este hilo puede que sea un método universal que sirva para determinar si un archivo de fuente contiene glifos para representar caracteres específicos (ej. "áéíóú"). Ya tengo algo hecho que funciona... pero no siempre funciona de la forma esperada (da falsos positivos con algunos archivos de fuente). Me falta mucho por aprender del formato TrueType y OpenType. Por suerte existen herramientas especializadas como por ejemplo "otfinfo.exe" (descarga) que sirven para obtener información general de una fuente, imprimir en consola los caracteres de un rango Unicode específico, volcar tablas completas y demás, y tener algo así me ayuda a hacer (y corregir) asunciones al leer este formato de archivo.

👋
9  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets) en: 31 Agosto 2025, 04:45 am
Métodos universales para trabajar aspectos básicos con fuentes de texto (.ttf, .otf y .fon).



Aspectos destacables del código

     ◉ Nombres descriptivos y documentación extensa, no creo que requieran ejemplos de uso (de todas formas no me cabrían en este post).

     ◉ Ligeras micro optimizaciones para .NET 5+ mediante directiva del preprocesador (#If NETCOREAPP...)

Incluye varios métodos para:

     ◉ Instalar/desinstalar una fuente solamente para el usuario local, o de forma global. Para esto último es posible requerir permisos de administrador.

     ◉ Determinar si una fuente está actualmente instalada en el sistema operativo,
         identificando varios aspectos como si el nombre del archivo o el nombre de la fuente están registradas en el Registro de Windows.

     ◉ Determinar el formato de un archivo de fuente.
         Soporta los formatos: TrueType (.ttf), OpenType con contornos TrueType (.ttf), OpenType PostScript (CFF) (.otf), y raster/bitmap (.fon).

     ◉ Obtener el nombre amistoso completo de una fuente de texto,
         exactamente tal y como se muestra en la barra de título del visor de fuentes de Windows (FontView.exe).

     ◉ Obtener el nombre del archivo de recurso de fuente escalable (.FOT) a partir de un archivo de fuente.

En torno a la instalación y desinstalación de fuentes:

     ◉ Al instalar una fuente permite cargarla en memoria, con lo cual se enviará el mensaje correspondiente a todas las ventanas del sistema operativo para notificar de un cambio (una nueva fuente disponible), de tal forma que otros programas puedan reconocer y utilizar dicha fuente.

     ◉ Al instalar una fuente se identifica correctamente el formato TrueType u OpenType y se registra apropiadamente en el nombre de la clave de registro correspondiente. Se puede anular este comportamiento mediante un parámetro Boolean para que siempre se añada el sufijo "(TrueType)" al nombre de la clave de registro tal y como lo hace la shell de Windows indiferentemente de si la fuente es OpenType. Esto no se aplica a fuentes raster/bitmap (.fon).

     ◉ Al desinstalar una fuente, permite eliminar el archivo. Si no se puede eliminar al primer intento, se detiene temporalmente el "Servicio de caché de fuentes de Windows" ('FontCache') para evitar posibles bloqueos y reintentar la eliminación. Al finalizar la desinstalación, se reanuda el servicio.



Diferencias en los nombres de fuentes

Para entrar en contexto y ver las diferencias en perspectiva, y tomando como ejemplo la fuente de texto OpenType PostScript (CFF) "JustBreatheBoldObliqueseven-7vgw.otf" (descarga), estos son los resultados:

 ◉ Nombre de la clave de registro al instalar la fuente de forma tradicional mediante la shell de Windows 10 (Menú contextual -> Instalar):
Código:
Just Breathe Bold ObliqueSeven (TrueType)
(sí, pone 'TrueType' a pesar de ser una fuente OpenType CFF, sin contornos TrueType.)


 ◉ Nombre mostrado en la barra de título del visor de fuentes de Microsoft Windows (FontView.exe)
Código:
Just Breathe Bold ObliqueSeven (OpenType)



 ◉ Nombre devuelto por mi función GetFontFriendlyName, con sufijo:
Código:
Just Breathe Bold ObliqueSeven (OpenType)
(Siempre debería devolver el mismo nombre que en el visor de fuentes de Microsoft Windows, eso sí, sin espacios en blanco adicionales al final del nombre ni antes del paréntesis del sufijo, cosa que FontView.exe no tiene en cuenta, pero mi código sí.
Lo he comparado programaticamente con aprox. 14.000 fuentes de texto para asegurarme de su fiabilidad.)

 ◉ Nombre devuelto por mi función GetFontFriendlyName, sin sufijo:
Código:
Just Breathe Bold ObliqueSeven

 ◉ Nombre devuelto por mi función GetFontResourceName:
Código:
JustBreatheBdObl7
(A veces, GetFontResourceName devolverá el mismo nombre que GetFontFriendlyName sin sufijo, es decir, el nombre escrito en el recurso de fuente escalable puede ser idéntico.)

 ◉ Nombre devuelto utilizando una combinación de propiedades de la clase System.Windows.Media.GlyphTypeface:
Código:
Just Breathe BdObl7

El código utilizado:
Código
  1. Dim fontUri As New Uri("C:\JustBreatheBoldObliqueseven-7vgw.otf", UriKind.Absolute)
  2. Dim gtf As New System.Windows.Media.GlyphTypeface(fontUri)
  3. Dim fontName As String = String.Join(" "c, gtf.FamilyNames.Values)
  4. Dim fontFaceNames As String = String.Join(" "c, gtf.FaceNames.Values)
  5. Dim fullName As String = $"{fontName} {fontFaceNames}"
  6. Console.WriteLine(fullName)

 ◉ Nombre devuelto por las propiedades System.Drawing.Font.Name y System.Drawing.FontFamily.Name:
Código:
Just Breathe

 ◉ Nombre devuelto por las propiedades System.Drawing.Font.OriginalName y System.Drawing.Font.SystemName
Código:
NINGUNO (VALOR VACÍO EN ESTE CASO CONCRETO)



Acerca de fontreg.exe

Existe una herramienta por línea de comandos llamada "fontreg.exe" (GitHub) que funciona como un sustituto moderno —aunque ya algo anticuado— del obsoleto fontinst.exe de Microsoft Windows. Sin embargo, no la recomiendo para instalar fuentes de forma programática.

Para un usuario común, esta herramienta será más que suficiente, pero para un programador no es lo ideal por las siguientes razones:

 ◉ Su funcionamiento requiere que "fontreg.exe" se coloque en el mismo directorio donde se encuentran las fuentes,
     y al ejecutarlo instalará todas las fuentes del directorio sin permitir seleccionar una instalación de fuentes individuales.
 ◉ El programa no imprime mensajes de salida que sirvan para depurar la operación de instalación.
 ◉ No puedes saber si la fuente se instalará solo para el usuario actual (HKCU) o de manera global en el sistema (HKLM).

Además, he detectado varios fallos:

 ◉ En ocasiones extrae incorrectamente el nombre de la fuente, y, debido a esto,
     en algunos casos termina escribiendo caracteres ininteligibles en la clave de registro, ej.: "⿻⿷⿸⿹ (TrueType)",
     y ese es el nombre que verás al listar la fuente en tu editor de texto.
 ◉ Al igual que la shell de Windows al registrar el nombre de una fuente en el registro de Windows,
     no hace distinción entre TrueType y OpenType: siempre se añade el sufijo "(TrueType)".

Por estas razones, su uso en entornos programáticos o controlados no es ni productivo, ni confiable.



El código completo semi-completo (he tenido que eliminar mucha documentación XML ya que no me cabía en este post):

Librerías (paquetes NuGet) necesarias:
 ◉ WindowsAPICodePack
 ◉ System.ServiceProcess.ServiceController (solo para usuarios de .NET 5+)

Imports necesarios:
Código
  1. #If NETCOREAPP Then
  2. Imports System.Buffers.Binary
  3. #End If
  4.  
  5. Imports System.ComponentModel
  6. Imports System.Diagnostics.CodeAnalysis
  7. Imports System.IO
  8. Imports System.Runtime.InteropServices
  9. Imports System.Runtime.Versioning
  10. Imports System.Security
  11. Imports System.ServiceProcess
  12. Imports System.Text
  13.  
  14. Imports Microsoft.Win32
  15.  
  16. Imports Microsoft.WindowsAPICodePack.Shell
  17.  
  18. Imports DevCase.Win32
  19. Imports DevCase.Win32.Enums

Clases secundarias requeridas:

Código
  1. #Region " Constants "
  2.  
  3. Namespace DevCase.Win32.Common.Constants
  4.  
  5.    <HideModuleName>
  6.    Friend Module Constants
  7.  
  8. #Region " Window Messaging "
  9.  
  10.        ''' <summary>
  11.        ''' Handle to use with window messaging functions.
  12.        ''' <para></para>
  13.        ''' When used, the message is sent to all top-level windows in the system,
  14.        ''' including disabled or invisible unowned windows, overlapped windows, and pop-up windows;
  15.        ''' but the message is not sent to child windows.
  16.        ''' </summary>
  17.        Friend ReadOnly HWND_BROADCAST As New IntPtr(65535US)
  18.  
  19. #End Region
  20.  
  21.    End Module
  22.  
  23. End Namespace
  24.  
  25. #End Region

Código
  1. #Region " Window Messages "
  2.  
  3. Namespace DevCase.Win32.Enums
  4.  
  5.    Friend Enum WindowMessages As Integer
  6.  
  7.        ''' <summary>
  8.        ''' An application sends the message to all top-level windows in the system after changing the
  9.        ''' pool of font resources.
  10.        ''' </summary>
  11.        WM_FontChange = &H1D
  12.  
  13.    End Enum
  14.  
  15. End Namespace
  16.  
  17. #End Region

Código
  1. #Region " NativeMethods "
  2.  
  3. Namespace DevCase.Win32.NativeMethods
  4.  
  5.    <SuppressUnmanagedCodeSecurity>
  6.    Friend Module Gdi32
  7.  
  8.        <DllImport("GDI32.dll", SetLastError:=False, CharSet:=CharSet.Auto, ThrowOnUnmappableChar:=True, BestFitMapping:=False)>
  9.        Friend Function AddFontResource(fileName As String
  10.        ) As Integer
  11.        End Function
  12.  
  13.        <DllImport("GDI32.dll", SetLastError:=True, CharSet:=CharSet.Auto, ThrowOnUnmappableChar:=True, BestFitMapping:=False)>
  14.        Friend Function RemoveFontResource(fileName As String
  15.        ) As <MarshalAs(UnmanagedType.Bool)> Boolean
  16.        End Function
  17.  
  18.    End Module
  19.  
  20.    <SuppressUnmanagedCodeSecurity>
  21.    Friend Module User32
  22.  
  23.        <DllImport("User32.dll", SetLastError:=True)>
  24.        Friend Function SendMessage(hWnd As IntPtr,
  25.                                    msg As WindowMessages,
  26.                                    wParam As IntPtr,
  27.                                    lParam As IntPtr
  28.        ) As IntPtr
  29.        End Function
  30.  
  31.    End Module
  32.  
  33. End Namespace
  34.  
  35. #End Region

Clase principal 'UtilFonts', que contiene los métodos universales (y otros miembros relacionados) en torno a fuentes de texto:

Código
  1. Public Class UtilFonts
  2.  
  3.    ''' <summary>
  4.    ''' Magic number located at the beginning of a TrueType font (.ttf) file header.
  5.    ''' </summary>
  6.    Private Shared ReadOnly TT_MAGIC As Byte() = {
  7.        &H0, &H1, &H0, &H0
  8.    }
  9.  
  10.    ''' <summary>
  11.    ''' Magic number located at the beginning of a TrueType font (.ttf) file header
  12.    ''' that starts with ASCII string "true".
  13.    ''' </summary>
  14.    Private Shared ReadOnly TT_MAGIC_TRUE As Byte() = {
  15.        &H74, &H72, &H75, &H65  ' "true"
  16.    }
  17.  
  18.    ''' <summary>
  19.    ''' Magic number located at the beginning of an OpenType font with CFF (PostScript) outlines (.otf) file header.
  20.    ''' <para></para>
  21.    ''' This distinguishes them from OpenType-TT fonts.
  22.    ''' </summary>
  23.    Private Shared ReadOnly OT_MAGIC As Byte() = {
  24.        &H4F, &H54, &H54, &H4F ' "OTTO"
  25.    }
  26.  
  27.    ''' <summary>
  28.    ''' Retrieves a user-friendly name for a given font file,
  29.    ''' that is identical to the 'Title' property shown by Windows Explorer,
  30.    ''' allowing to provide consistent font identification in your application.  
  31.    ''' </summary>
  32.    '''
  33.    ''' <param name="fontFile">
  34.    ''' The path to the font file (e.g., <b>"C:\font.ttf"</b>).
  35.    ''' </param>
  36.    '''
  37.    ''' <param name="includeSuffix">
  38.    ''' If <see langword="True"/>, includes a suffix that specifies
  39.    ''' the underlying font technology (e.g., "Font name <c>(TrueType)</c>", "Font name <c>(OpenType)</c>"),
  40.    ''' ensuring that the font name matches exactly the name shown in Microsoft's Windows Font Viewer (FontView.exe) title bar.
  41.    ''' </param>
  42.    '''
  43.    ''' <returns>
  44.    ''' The user-friendly name for the given font file.
  45.    ''' </returns>
  46.    <DebuggerStepThrough>
  47.    Public Shared Function GetFontFriendlyName(fontFile As String, includeSuffix As Boolean) As String
  48.  
  49.        If Not File.Exists(fontFile) Then
  50.            Dim msg As String = $"The font file does not exist: '{fontFile}'"
  51.            Throw New FileNotFoundException(msg, fontFile)
  52.        End If
  53.  
  54.        Dim fontTitle As String = ShellFile.FromFilePath(fontFile).Properties.System.Title.Value.Trim()
  55.        If String.IsNullOrWhiteSpace(fontTitle) Then
  56.            Dim msg As String = "'Title' property for the given font is empty."
  57.            Throw New FormatException(msg)
  58.        End If
  59.  
  60.        If includeSuffix Then
  61.            Dim fontType As FontType = UtilFonts.GetFontType(fontFile)
  62.            Select Case fontType
  63.  
  64.                Case FontType.Invalid
  65.                    Dim msg As String = "File does not seems a valid font file (file size is too small)."
  66.                    Throw New FileFormatException(msg)
  67.  
  68.                Case FontType.Unknown
  69.                    Dim msg As String = "Font file type is not recognized. " &
  70.                                        "It might be an unsupported format, corrupted file Or Not a valid font file."
  71.                    Throw New FileFormatException(msg)
  72.  
  73.                Case FontType.TrueType
  74.                    Return $"{fontTitle} (TrueType)"
  75.  
  76.                Case FontType.OpenTypeCFF, FontType.OpenTypeTT
  77.                    Return $"{fontTitle} (OpenType)"
  78.  
  79.                Case Else ' FontType.Raster
  80.                    ' Nothing to do.
  81.            End Select
  82.        End If
  83.  
  84.        Return fontTitle
  85.    End Function
  86.  
  87.    ''' <summary>
  88.    ''' Determines the type of a font file.
  89.    ''' <para></para>
  90.    ''' Supports TrueType (.ttf), OpenType (.otf/.ttf) and Raster/Bitmap (.fon).
  91.    ''' </summary>
  92.    '''
  93.    ''' <param name="fontFile">
  94.    ''' The path to the font file (e.g., <b>"C:\font.ttf"</b>).
  95.    ''' </param>
  96.    '''
  97.    ''' <returns>
  98.    ''' A <see cref="FontType"/> value indicating the font type of the given file.
  99.    ''' <para></para>
  100.    ''' If the font type cannot be recognized, it returns <see cref="FontType.Unknown"/>.
  101.    ''' <para></para>
  102.    ''' If the given file does not meet the criteria to be treated as a font file, it returns <see cref="FontType.Invalid"/>.
  103.    ''' </returns>
  104.    <DebuggerStepThrough>
  105.    Public Shared Function GetFontType(fontFile As String) As FontType
  106.  
  107.        If Not File.Exists(fontFile) Then
  108.            Dim msg As String = $"The font file does not exist: '{fontFile}'"
  109.            Throw New FileNotFoundException(msg, fontFile)
  110.        End If
  111.  
  112.        ' 512 bytes is the minimum length I found sufficient
  113.        ' to reliably read the header of any raster (.fon) font file
  114.        ' to find its string markers that identifies this file type.
  115.        Const minFontFileLength As Short = 512
  116.  
  117.        Dim fi As New FileInfo(fontFile)
  118.        If fi.Length <= minFontFileLength Then
  119.            Return FontType.Invalid
  120.        End If
  121.  
  122.        Try
  123.            Using fs As FileStream = fi.OpenRead(),
  124.                  br As New BinaryReader(fs)
  125.  
  126.                Dim headerBytes As Byte() = br.ReadBytes(4)
  127.  
  128.                ' TrueType check.
  129.                If headerBytes.SequenceEqual(UtilFonts.TT_MAGIC) OrElse
  130.                   headerBytes.SequenceEqual(UtilFonts.TT_MAGIC_TRUE) Then
  131.  
  132.                    ' OpenType-TT check
  133.                    br.BaseStream.Seek(4, SeekOrigin.Begin)
  134. #If NETCOREAPP Then
  135.                    Dim numTables As UShort = BinaryPrimitives.ReverseEndianness(br.ReadUInt16())
  136. #Else
  137.                    ' Read two bytes directly.
  138.                    Dim bytes As Byte() = br.ReadBytes(2)
  139.                    ' If the system is little-endian, reverse the bytes to interpret as big-endian.
  140.                    If BitConverter.IsLittleEndian Then
  141.                        Array.Reverse(bytes)
  142.                    End If
  143.                    ' Now get the UShort value in big-endian.
  144.                    Dim swapped As UShort = BitConverter.ToUInt16(bytes, 0)
  145.                    Dim numTables As UShort = swapped
  146. #End If
  147.                    br.BaseStream.Seek(6, SeekOrigin.Current) ' skip: searchRange, entrySelector, rangeShift
  148.                    ' Search advanced OpenType tables.
  149.                    For i As Integer = 0 To numTables - 1
  150.                        Dim tag As String = Encoding.ASCII.GetString(br.ReadBytes(4))
  151.                        br.ReadBytes(12) ' checkSum, offset, length
  152.                        If tag = "GSUB" OrElse tag = "GPOS" OrElse tag = "GDEF" OrElse tag = "BASE" Then
  153.                            Return FontType.OpenTypeTT
  154.                        End If
  155.                    Next
  156.  
  157.                    Return FontType.TrueType
  158.                End If
  159.  
  160.                ' OpenType CFF check.
  161.                If headerBytes.SequenceEqual(UtilFonts.OT_MAGIC) Then
  162.                    Return FontType.OpenTypeCFF
  163.                End If
  164.  
  165.                ' Raster/Bitmap check.
  166.                br.BaseStream.Seek(0, SeekOrigin.Begin)
  167.                headerBytes = br.ReadBytes(minFontFileLength)
  168.                Dim headerText As String = Encoding.ASCII.GetString(headerBytes)
  169.                If headerText.Contains("FONTDIR") AndAlso
  170.                   headerText.Contains("FONTRES") Then
  171.                    Return FontType.Raster
  172.                End If
  173.  
  174.            End Using
  175.  
  176.        Catch ex As Exception
  177.            Throw
  178.  
  179.        End Try
  180.  
  181.        Return FontType.Unknown
  182.    End Function
  183.  
  184.    ''' <summary>
  185.    ''' Specifies the type of a font file.
  186.    ''' </summary>
  187.    Public Enum FontType As Short
  188.  
  189.        ''' <summary>
  190.        ''' A TrueType font (.ttf).
  191.        ''' <para></para>
  192.        ''' This is the traditional TrueType format developed by Apple™.
  193.        ''' </summary>
  194.        TrueType
  195.  
  196.        ''' <summary>
  197.        ''' An OpenType font with PostScript (CFF) outlines (.otf).
  198.        ''' <para></para>
  199.        ''' These fonts use the .otf container from the OpenType format jointly developed by Adobe™ and Microsoft™.
  200.        ''' </summary>
  201.        OpenTypeCFF
  202.  
  203.        ''' <summary>
  204.        ''' An OpenType font with TrueType outlines (.ttf).
  205.        ''' <para></para>
  206.        ''' Technically OpenType, but uses TrueType outlines inside a .ttf container.
  207.        ''' <para></para>
  208.        ''' Sometimes called 'OpenType-TT' for distinction.
  209.        ''' </summary>
  210.        OpenTypeTT
  211.  
  212.        ''' <summary>
  213.        ''' A Raster / Bitmap font (.fon) with fixed-size glyphs.
  214.        ''' <para></para>
  215.        ''' Raster fonts store each character as a pixel grid, not as scalable outlines.
  216.        ''' <para></para>
  217.        ''' These were commonly used in older versions of Windows and DOS, and are mostly legacy fonts today.
  218.        ''' </summary>
  219.        Raster
  220.  
  221.        ''' <summary>
  222.        ''' Font file type is not recognized.
  223.        ''' <para></para>
  224.        ''' It might be an unsupported format, corrupted file or not a valid font file.
  225.        ''' </summary>
  226.        Unknown
  227.  
  228.        ''' <summary>
  229.        ''' File does not seems a valid font file (file size is too small).
  230.        ''' </summary>
  231.        Invalid
  232.  
  233.    End Enum
  234.  
  235.    ''' <summary>
  236.    ''' Determines whether a font file is already installed in the current computer.
  237.    ''' </summary>
  238.    '''
  239.    ''' <param name="fontFilePathOrName">
  240.    ''' Either the full path to the font file or just the file name
  241.    ''' (e.g., <b>"C:\font.ttf"</b> or else <b>"font.ttf"</b>).
  242.    ''' </param>
  243.    '''
  244.    ''' <param name="systemWide">
  245.    ''' If <see langword="True"/>, performs a system-wide search for the font installation (under <c>HKEY_LOCAL_MACHINE</c> base key).
  246.    ''' otherwise, searches only the current user's installed fonts (under <c>HKEY_CURRENT_USER</c> base key).
  247.    ''' </param>
  248.    '''
  249.    ''' <returns>
  250.    ''' If the font file is not installed, returns <see cref="CheckFontInstallationResults.NotInstalled"/>;
  251.    ''' otherwise, can return a combination of <see cref="CheckFontInstallationResults"/> values.
  252.    ''' </returns>
  253.    <DebuggerStepThrough>
  254.    Public Shared Function CheckFontInstallation(fontFilePathOrName As String, systemWide As Boolean) As CheckFontInstallationResults
  255.  
  256.        Dim fontFilePath As String = UtilFonts.BuildFullFontFilePath(fontFilePathOrName, systemWide)
  257.        Dim fontFileName As String = Path.GetFileName(fontFilePath)
  258.        Dim fontTitle As String = UtilFonts.GetFontFriendlyName(fontFilePath, includeSuffix:=False)
  259.  
  260.        Dim fontTitleTT As String = $"{fontTitle} (TrueType)"
  261.        Dim fontTitleOT As String = $"{fontTitle} (OpenType)"
  262.  
  263.        Dim result As CheckFontInstallationResults = CheckFontInstallationResults.NotInstalled
  264.  
  265.        Dim baseKey As RegistryKey = If(systemWide, Registry.LocalMachine, Registry.CurrentUser)
  266.        Dim regKeyPath As String = "SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts"
  267.  
  268.        Try
  269.            Using key As RegistryKey = baseKey.OpenSubKey(regKeyPath, writable:=False)
  270.                ' Fonts registry key does not exists.
  271.                If key Is Nothing Then
  272.                    Exit Try
  273.                End If
  274.  
  275.                Dim valueFontTitle As Object = CStr(key.GetValue(fontTitle))
  276.                Dim valueFontTitleTT As Object = CStr(key.GetValue(fontTitleTT))
  277.                Dim valueFontTitleOT As Object = CStr(key.GetValue(fontTitleOT))
  278.  
  279.                Dim fontTitles() As String = {fontTitle, fontTitleTT, fontTitleOT}
  280.                For Each title As String In fontTitles
  281.  
  282.                    Dim regValue As Object = key.GetValue(title, Nothing, RegistryValueOptions.DoNotExpandEnvironmentNames)
  283.  
  284.                    ' Font title found in registry
  285.                    If regValue IsNot Nothing Then
  286.                        result = result Or CheckFontInstallationResults.FontTitleFound
  287.  
  288.                        ' Font file matches?
  289.                        If String.Equals(CStr(regValue), fontFileName, StringComparison.OrdinalIgnoreCase) Then
  290.                            result = result Or CheckFontInstallationResults.FileNameFound
  291.                        End If
  292.                    End If
  293.  
  294.                    If result = (CheckFontInstallationResults.FontTitleFound Or CheckFontInstallationResults.FileNameFound) Then
  295.                        Exit For
  296.                    End If
  297.                Next
  298.  
  299.                If Not result.HasFlag(CheckFontInstallationResults.FileNameFound) Then
  300.                    ' Additional check required for consistency because the font file name
  301.                    ' could be specified in a value name that differs from the compared font title vale names.
  302.                    Dim valueNames As String() = Array.ConvertAll(key.GetValueNames(), Function(str As String) str.ToLowerInvariant())
  303.                    If valueNames.Contains(fontFileName.ToLowerInvariant()) Then
  304.                        result = result Or CheckFontInstallationResults.FileNameFound
  305.                    End If
  306.                End If
  307.  
  308.            End Using
  309.  
  310.        Catch ex As Exception
  311.            Throw
  312.  
  313.        End Try
  314.  
  315.        Return result
  316.    End Function
  317.  
  318.    ''' <summary>
  319.    ''' Specifies the installation status of a font file on the current computer.
  320.    ''' </summary>
  321.    <Flags>
  322.    Public Enum CheckFontInstallationResults As Short
  323.  
  324.        ''' <summary>
  325.        ''' The font is not installed.
  326.        ''' </summary>
  327.        NotInstalled = 0S
  328.  
  329.        ''' <summary>
  330.        ''' A registry value with the font file name is present in the Windows <b>Fonts</b> registry key.
  331.        ''' </summary>
  332.        FileNameFound = 1S << 0S
  333.  
  334.        ''' <summary>
  335.        ''' A registry value name with the font title
  336.        ''' (which also may have suffix: "<b>(TrueType)</b>" or "<b>(OpenType)</b>")
  337.        ''' is present in the Windows <b>Fonts</b> registry key.
  338.        ''' </summary>
  339.        FontTitleFound = 1S << 1S
  340.  
  341.    End Enum
  342.  
  343.    ''' <summary>
  344.    ''' Installs a font file permanently on the current computer.
  345.    ''' </summary>
  346.    '''
  347.    ''' <param name="fontFile">
  348.    ''' The path to the font file to install (e.g., <b>"C:\font.ttf"</b>).
  349.    ''' </param>
  350.    '''
  351.    ''' <param name="systemWide">
  352.    ''' If <see langword="True"/>, performs a system-wide installation;
  353.    ''' otherwise, installs the font for the current user only.
  354.    ''' </param>
  355.    '''
  356.    ''' <param name="useTrueTypeNameSuffix">
  357.    ''' If <see langword="True"/>, appends the "<b>(TrueType)</b>" suffix when
  358.    ''' naming the font registry value for TrueType and OpenType fonts.
  359.    ''' This is what Microsoft Windows does by default.
  360.    ''' <para></para>
  361.    ''' If <see langword="False"/>, appends the appropriate suffix for the font type: "<b>(TrueType)</b>" or "<b>(OpenType)</b>".
  362.    ''' <para></para>
  363.    ''' This setting does not apply to .fon files.
  364.    ''' </param>
  365.    '''
  366.    ''' <param name="addFontToSystemTable">
  367.    ''' If <see langword="True"/>, the font resource is loaded into memory and immediately available to other applications.
  368.    ''' </param>
  369.    <DebuggerStepThrough>
  370.    Public Shared Sub InstallFont(fontFile As String, systemWide As Boolean, useTrueTypeNameSuffix As Boolean, addFontToSystemTable As Boolean)
  371.  
  372.        Dim isFontInstalled As Boolean
  373.        Try
  374.            isFontInstalled = (UtilFonts.CheckFontInstallation(fontFile, systemWide) <> UtilFonts.CheckFontInstallationResults.NotInstalled)
  375.  
  376.        Catch ex As FileNotFoundException
  377.            ' Use this exception message for readness, since CheckFontInstallation calls BuildFullFontFilePath, which modifies the path.
  378.            Dim msg As String = $"The font file does not exist: '{fontFile}'"
  379.            Throw New FileNotFoundException(msg, fontFile)
  380.  
  381.        Catch ex As Exception
  382.            Throw
  383.        End Try
  384.  
  385.        If isFontInstalled Then
  386.            Dim msg As String = $"The font file is already installed: '{fontFile}'"
  387.            Throw New InvalidOperationException(msg)
  388.        End If
  389.  
  390.        Dim fontFileName As String = Path.GetFileName(fontFile)
  391.        Dim fontTitle As String = UtilFonts.GetFontFriendlyName(fontFile, includeSuffix:=True)
  392.        If useTrueTypeNameSuffix Then
  393.            fontTitle = fontTitle.Replace(" (OpenType)", " (TrueType)")
  394.        End If
  395.  
  396.        Dim fontsDir As String = If(systemWide,
  397.            Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Fonts"),
  398.            Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Microsoft\Windows\Fonts"))
  399.  
  400.        If Not Directory.Exists(fontsDir) Then
  401.            Directory.CreateDirectory(fontsDir)
  402.        End If
  403.  
  404.        Dim fontFileDestPath As String = Path.Combine(fontsDir, fontFileName)
  405.        If File.Exists(fontFileDestPath) Then
  406.            Dim msg As String = $"Font file already exists in Fonts directory: {fontFileDestPath}"
  407.            Throw New InvalidOperationException(msg)
  408.        End If
  409.  
  410.        Try
  411.            File.Copy(fontFile, fontFileDestPath, overwrite:=False)
  412.        Catch ex As Exception
  413.            Dim msg As String = $"Error copying font file to Fonts directory: '{fontFileDestPath}'"
  414.            Throw New IOException(msg, ex)
  415.        End Try
  416.  
  417.        Dim baseKey As RegistryKey = If(systemWide, Registry.LocalMachine, Registry.CurrentUser)
  418.        Dim regKeyPath As String = "SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts"
  419.  
  420.        Dim registrySuccess As Boolean
  421.        Try
  422.            Using key As RegistryKey = baseKey.CreateSubKey(regKeyPath, writable:=True)
  423.                key.SetValue(fontTitle, fontFileName, RegistryValueKind.String)
  424.            End Using
  425.            registrySuccess = True
  426.  
  427.        Catch ex As Exception
  428.            Throw
  429.  
  430.        Finally
  431.            If Not registrySuccess Then
  432.                ' Attempt to delete the copied font file in Fonts directory
  433.                ' when registry manipulation has failed.
  434.                Try
  435.                    File.Delete(fontFileDestPath)
  436.                Catch
  437.                    ' Ignore deletion exceptions; cleanup best effort.
  438.                End Try
  439.            End If
  440.        End Try
  441.  
  442.        ' Add the font to the system font table.
  443.        If addFontToSystemTable Then
  444.            Dim fontsAdded As Integer = DevCase.Win32.NativeMethods.AddFontResource(fontFileDestPath)
  445.            Dim win32Err As Integer = Marshal.GetLastWin32Error()
  446.  
  447.            If fontsAdded = 0 OrElse win32Err <> 0 Then
  448.                Dim msg As String = $"Failed to add font to the system font table '{fontFileDestPath}'"
  449.                Throw New InvalidOperationException(msg, New Win32Exception(win32Err))
  450.            End If
  451.  
  452.            ' Notify all top-level windows so they can immediately list the added font.
  453.            DevCase.Win32.NativeMethods.SendMessage(DevCase.Win32.Common.Constants.HWND_BROADCAST, WindowMessages.WM_FontChange, IntPtr.Zero, IntPtr.Zero)
  454.        End If
  455.  
  456.    End Sub
  457.  
  458.    ''' <summary>
  459.    ''' Uninstalls a font file from the current computer.
  460.    ''' </summary>
  461.    '''
  462.    ''' <param name="fontFilePathOrName">
  463.    ''' Either the full path to the font file or just the file name
  464.    ''' (e.g., <b>"C:\font.ttf"</b> or else <b>"font.ttf"</b>).
  465.    ''' </param>
  466.    '''
  467.    ''' <param name="systemWide">
  468.    ''' If <see langword="True"/>, performs a system-wide uninstallation;
  469.    ''' otherwise, uninstalls the font for the current user only.
  470.    ''' </param>
  471.    '''
  472.    ''' <param name="deleteFile">
  473.    ''' If <see langword="True"/>, permanently deletes the font file from disk.
  474.    ''' <para></para>
  475.    ''' Note: The font file deletion will be performed after deleting associated registry values with the font file.
  476.    ''' </param>
  477.    <DebuggerStepThrough>
  478.    Public Shared Sub UninstallFont(fontFilePathOrName As String, systemWide As Boolean, deleteFile As Boolean)
  479.  
  480.        Dim fontFilePath As String = UtilFonts.BuildFullFontFilePath(fontFilePathOrName, systemWide)
  481.        Dim fontFileName As String = Path.GetFileName(fontFilePath)
  482.  
  483.        Dim checkFontInstallation As CheckFontInstallationResults = UtilFonts.CheckFontInstallation(fontFilePath, systemWide)
  484.        Dim isFontInstalled As Boolean = (checkFontInstallation <> UtilFonts.CheckFontInstallationResults.NotInstalled)
  485.        If Not isFontInstalled Then
  486.            Dim msg As String = $"The font file is not installed: '{fontFilePath}'"
  487.            Throw New InvalidOperationException(msg)
  488.        End If
  489.  
  490.        Dim fontTitle As String = UtilFonts.GetFontFriendlyName(fontFilePath, includeSuffix:=False)
  491.        Dim fontTitleTT As String = $"{fontTitle} (TrueType)"
  492.        Dim fontTitleOT As String = $"{fontTitle} (OpenType)"
  493.  
  494.        Dim baseKey As RegistryKey = If(systemWide, Registry.LocalMachine, Registry.CurrentUser)
  495.        Dim regKeyPath As String = "SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts"
  496.  
  497.        Try
  498.            Using key As RegistryKey = baseKey.OpenSubKey(regKeyPath, writable:=True)
  499.  
  500.                Dim valueNames As String() = key.GetValueNames()
  501.  
  502.                ' Compare font title.
  503.                If checkFontInstallation.HasFlag(CheckFontInstallationResults.FontTitleFound) Then
  504.                    If valueNames.Contains(fontTitle) Then
  505.                        key.DeleteValue(fontTitle, throwOnMissingValue:=True)
  506.  
  507.                    ElseIf valueNames.Contains(fontTitleTT) Then
  508.                        key.DeleteValue(fontTitleTT, throwOnMissingValue:=True)
  509.  
  510.                    ElseIf valueNames.Contains(fontTitleOT) Then
  511.                        key.DeleteValue(fontTitleOT, throwOnMissingValue:=True)
  512.  
  513.                    End If
  514.  
  515.                ElseIf checkFontInstallation.HasFlag(CheckFontInstallationResults.FileNameFound) Then
  516.                    For Each valueName As String In valueNames
  517.                        ' Compare font file name.
  518.                        Dim value As String = CStr(key.GetValue(valueName))
  519.                        If String.Equals(value, fontFileName, StringComparison.OrdinalIgnoreCase) Then
  520.                            key.DeleteValue(valueName, throwOnMissingValue:=True)
  521.                            Exit For
  522.                        End If
  523.                    Next
  524.  
  525.                End If
  526.  
  527.            End Using
  528.  
  529.        Catch ex As Exception
  530.            Throw
  531.  
  532.        End Try
  533.  
  534.        If deleteFile Then
  535.            Dim fontsDir As String = If(systemWide,
  536.                Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Fonts"),
  537.                Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Microsoft\Windows\Fonts"))
  538.  
  539.            Dim fontFileDestPath As String = Path.Combine(fontsDir, fontFileName)
  540.  
  541.            ' First attempt to delete the file.
  542.            Try
  543.                File.Delete(fontFileDestPath)
  544.            Catch
  545.            End Try
  546.  
  547.            If File.Exists(fontFileDestPath) Then
  548.                ' Remove the font from the system font table,
  549.                ' because in case of 'AddFontResource' was called for this font file in the current user session,
  550.                ' the font will remain loaded in memory and cannot be deleted until unloaded from memory.
  551.                Dim result As Boolean = DevCase.Win32.NativeMethods.RemoveFontResource(fontFileDestPath)
  552.                Dim win32Err As Integer = Marshal.GetLastWin32Error()
  553.  
  554.                If result Then
  555.                    ' Notify all top-level windows so they can immediately delist the removed font.
  556.                    DevCase.Win32.NativeMethods.SendMessage(DevCase.Win32.Common.Constants.HWND_BROADCAST, WindowMessages.WM_FontChange, IntPtr.Zero, IntPtr.Zero)
  557.                Else
  558.                    ' Ignore throwing an exception, since we don't really know if the font file was loaded in memory.
  559.  
  560.                    'Dim msg As String = $"Failed to remove font file from the system font table: '{fontFileDestPath}'"
  561.                    'Throw New InvalidOperationException(msg, New Win32Exception(win32Err))
  562.                End If
  563.  
  564.                ' Second attempt to delete the file.
  565.                Try
  566.                    File.Delete(fontFileDestPath)
  567.                Catch
  568.                End Try
  569.  
  570.            End If
  571.  
  572.            If File.Exists(fontFileDestPath) Then
  573.  
  574.                ' Ensure that the 'FontCache' service is stopped, as it could habe blocked the font file.
  575.                Using sc As New ServiceController("FontCache")
  576.                    Dim previousStatus As ServiceControllerStatus = sc.Status
  577.                    If (sc.Status <> ServiceControllerStatus.Stopped) AndAlso
  578.                       (sc.Status <> ServiceControllerStatus.StopPending) Then
  579.                        Try
  580.                            sc.Stop()
  581.                            sc.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(3))
  582.                        Catch ex As Exception
  583.                            ' Ignore throwing an exception,
  584.                            ' since we don't really know if the 'FontCache' service have blocked the font file at all.
  585.  
  586.                            'If sc.Status <> ServiceControllerStatus.Stopped Then
  587.                            '    Dim msg As String = "Unable to stop 'FontCache' service."
  588.                            '    Throw New InvalidOperationException(msg, ex)
  589.                            'End If
  590.                        End Try
  591.                    End If
  592.  
  593.                    ' Third and last attempt to delete the file.
  594.                    Try
  595.                        File.Delete(fontFileDestPath)
  596.  
  597.                    Catch ex As Exception
  598.                        Dim msg As String = $"Error deleting font file from Fonts directory: '{fontFileDestPath}'"
  599.                        Throw New IOException(msg, ex)
  600.  
  601.                    Finally
  602.                        ' Restore previous 'FontCache' service status if it was started and not in automatic mode.
  603.                        If sc.StartType <> ServiceStartMode.Automatic AndAlso (
  604.                              (previousStatus = ServiceControllerStatus.Running) OrElse
  605.                              (previousStatus = ServiceControllerStatus.StartPending)
  606.                           ) AndAlso sc.Status <> ServiceControllerStatus.Running Then
  607.                            Try
  608.                                sc.Start()
  609.                                sc.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(0.25))
  610.                            Catch
  611.                                ' Ignore throwing an exception; best effort.
  612.                            End Try
  613.                        End If
  614.                    End Try
  615.                End Using
  616.            End If
  617.  
  618.        End If
  619.  
  620.    End Sub
  621.  
  622.    ''' <summary>
  623.    ''' Builds a full path to a font file from the given value in <paramref name="fontFilePathOrName"/> parameter.
  624.    ''' <para></para>
  625.    ''' If the provided file path exists, it is returned as-is; otherwise,
  626.    ''' the function constructs and returns a full file path based on
  627.    ''' the value of <paramref name="systemWide"/> parameter.
  628.    ''' <para></para>
  629.    ''' Note: This function does not check whether the resulting file path exists.
  630.    ''' </summary>
  631.    '''
  632.    ''' <param name="fontFilePathOrName">
  633.    ''' Either the full path to the font file or just the file name
  634.    ''' (e.g., <b>"C:\font.ttf"</b> or else <b>"font.ttf"</b>).
  635.    ''' <para></para>
  636.    ''' If the provided path exists, the function returns this path as-is.
  637.    ''' </param>
  638.    '''
  639.    ''' <param name="systemWide">
  640.    ''' If <see langword="True"/>, the function constructs a full font file path from the system's Fonts directory
  641.    ''' (<b>%WINDIR%\Fonts</b>); otherwise, it constructs a full font file path from the current user's local Fonts directory
  642.    ''' (<b>%LOCALAPPDATA%\Microsoft\Windows\Fonts</b>).
  643.    ''' <para></para>
  644.    ''' Note: The <paramref name="systemWide"/> parameter is ignored if
  645.    ''' <paramref name="fontFilePathOrName"/> already specifies an existing file path.
  646.    ''' </param>
  647.    '''
  648.    ''' <returns>
  649.    ''' The resulting full path to the font file.
  650.    ''' </returns>
  651.    <DebuggerStepThrough>
  652.    Private Shared Function BuildFullFontFilePath(fontFilePathOrName As String, systemWide As Boolean) As String
  653.  
  654.        If File.Exists(fontFilePathOrName) Then
  655.            Return fontFilePathOrName
  656.        End If
  657.  
  658.        Dim fontFileName As String = Path.GetFileName(fontFilePathOrName)
  659.        If String.IsNullOrWhiteSpace(fontFileName) Then
  660.            Throw New ArgumentException("The font file path or name is malformed or empty.", NameOf(fontFilePathOrName))
  661.        End If
  662.  
  663.        Dim fontsDir As String = If(systemWide,
  664.            Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Fonts"),
  665.            Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Microsoft\Windows\Fonts"))
  666.  
  667.        Return Path.Combine(fontsDir, fontFileName)
  668.    End Function
  669.  
  670. End Class

El código continúa aquí abajo 👇🙂
10  Foros Generales / Foro Libre / Re: Viaje a la nueva Corea del Norte: ¿un paraíso turístico del comunismo? en: 30 Agosto 2025, 22:59 pm
Os podria explicar mil historias sobre él.
(...)
Sobre su etapa como militar español, lo que yo vi y lo que cuenta; son dos versiones muy distintas.

Pues hombre, si lo redactas bien, yo creo que sería interesante conocer historias de la mili. Eso sí, en un hilo dedicado a ello. De hecho creo que es una muy buena idea un hilo donde la gente pudiera contar sus experiencias en la mili española, o en las fuerzas militares de otro país ¿no?. Para avivar un poco el foro.

PD: yo a esa persona nunca antes la había visto en Internet, simplemente busqué videos de Corea del Norte y encontré eso.

Saludos
Páginas: [1] 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ... 1254
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines