|
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: Add-Type -AssemblyName System.Drawing Add-Type -AssemblyName System.Windows.Forms Add-Type @" using System; using System.Runtime.InteropServices; public static class WinAPI { [DllImport("kernel32.dll")] public static extern IntPtr GetConsoleWindow(); [DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); [DllImport("shell32.dll", CharSet=CharSet.Unicode)] public static extern int ExtractIconEx(string lpszFile, int nIconIndex, out IntPtr phiconLarge, out IntPtr phiconSmall, int nIcons); [DllImport("user32.dll", CharSet=CharSet.Auto)] public static extern bool DestroyIcon(IntPtr handle); } "@ # --- SINGLE INSTANCE CHECK THROUGH MUTEX --- $mutexName = "Global\ComputerUptimeFormMutex" $createdNew = $false $mutex = New-Object System.Threading.Mutex($true, $mutexName, [ref]$createdNew) if (-not $createdNew) { [System.Windows.Forms.MessageBox]::Show( "Only one instance of this program is allowed.", "Computer Uptime", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Stop ) } # --- HIDE CURRENT POWERSHELL CONSOLE --- $SW_HIDE = 0 $hWnd = [WinAPI]::GetConsoleWindow() [WinAPI]::ShowWindow($hWnd, $SW_HIDE) | Out-Null # --- CREATE THE FORM --- $form = New-Object System.Windows.Forms.Form $form.Text = "Computer Uptime" $form.Size = New-Object System.Drawing.Size(350, 150) $form.StartPosition = "CenterScreen" $form.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedDialog $form.MaximizeBox = $false $form.MinimizeBox = $true $form.Padding = New-Object System.Windows.Forms.Padding(4) $form.DoubleBuffered = $true # --- SET FORM ICON --- $shell32 = "$env:SystemRoot\System32\shell32.dll" $hLarge = [IntPtr]::Zero $hSmall = [IntPtr]::Zero $iconIndex = 265 # A clock icon in Windows 10. [WinAPI]::ExtractIconEx($shell32, $iconIndex, [ref]$hLarge, [ref]$hSmall, 1) | Out-Null if ($hSmall -ne [IntPtr]::Zero) { $form.Icon = [System.Drawing.Icon]::FromHandle($hSmall) } # --- LABEL TO DISPLAY UPTIME --- $label = New-Object System.Windows.Forms.Label $label.Font = New-Object System.Drawing.Font("Segoe UI", 14, [System.Drawing.FontStyle]::Bold) $label.Dock = [System.Windows.Forms.DockStyle]::Fill $label.TextAlign = [System.Drawing.ContentAlignment]::MiddleCenter $label.AutoSize = $false $label.DoubleBuffered = $true $form.Controls.Add($label) # --- GET SYSTEM INFORMATION FROM WMI --- $os = Get-CimInstance Win32_OperatingSystem $bootTime = $os.LastBootUpTime $computerName = $os.CSName # --- TIMER TO UPDATE UPTIME --- $timer = New-Object System.Windows.Forms.Timer $timer.Interval = 100 $timer.Add_Tick({ $uptime = (Get-Date) - $bootTime $minutes = $uptime.Minutes.ToString("00") $seconds = $uptime.Seconds.ToString("00") $milliseconds = $uptime.Milliseconds.ToString("000") $label.Text = "$computerName`n`n$($uptime.Days) days — $($uptime.Hours)h : $($minutes)m : $($seconds)s : $($milliseconds)ms" }) $timer.Start() # --- RELEASE ICON HANDLES AND MUTEX WHEN FORM GETS CLOSED --- $form.Add_FormClosed({ if ($hSmall -ne [IntPtr]::Zero) { [WinAPI]::DestroyIcon($hSmall) } if ($hLarge -ne [IntPtr]::Zero) { [WinAPI]::DestroyIcon($hLarge) } $mutex.ReleaseMutex() }) # --- SHOW THE FORM --- [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. Option Explicit Dim oneMinute, oneHour, oneDay: oneMinute = 60: oneHour = 3600: oneDay = 86400 Dim objWMIService, colOperatingSystems, objOperatingSystem Dim computerName, lastBootUpTime, upTime Set objWMIService = GetObject("winmgmts:\\.\root\cimv2") Set colOperatingSystems = objWMIService.ExecQuery("Select * from Win32_OperatingSystem") For Each objOperatingSystem In colOperatingSystems computerName = objOperatingSystem.CSName lastBootUpTime = objOperatingSystem.LastBootUpTime lastBootUpTime = CDate(Mid(lastBootUpTime, 1, 4) & "/" & Mid(lastBootUpTime, 5, 2) & "/" & Mid(lastBootUpTime, 7, 2) & " " & _ Mid(lastBootUpTime, 9, 2) & ":" & Mid(lastBootUpTime, 11, 2) & ":" & Mid(lastBootUpTime, 13, 2)) upTime = DateDiff("s", lastBootUpTime, Now) MsgBox computerName & vbCrLf & vbCrLf & _ upTime \ oneDay & " days ~ " & _ (upTime Mod oneDay) \ oneHour & "h : " & _ (upTime Mod oneHour) \ oneMinute & "m : " & _ upTime Mod oneMinute & "s", vbInformation, "Computer Uptime" Next 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 sí 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. 🙏Public Class UtilFonts ''' <summary> ''' Prevents a default instance of the <see cref="UtilFonts"/> class from being created. ''' </summary> Private Sub New() End Sub ''' <summary> ''' Retrieves the raw outline data for a given glyph from the specified font file. ''' <para></para> ''' This function calls <see cref="DevCase.Win32.NativeMethods.GetGlyphOutline"/> in background ''' to retrieve outline data with the requested <paramref name="format"/>. ''' </summary> ''' ''' <param name="fontFile"> ''' Path to the font file from which the glyph will be obtained. ''' </param> ''' ''' <param name="ch"> ''' The character whose glyph outline will be requested. ''' </param> ''' ''' <param name="format"> ''' The format in which the glyph outline will be retrieved. ''' <para></para> ''' This value only can be <see cref="GetGlyphOutlineFormat.Native"/> or <see cref="GetGlyphOutlineFormat.Bezier"/>. ''' <para></para> ''' Note: callers must interpret the returned byte array based on the selected format. ''' </param> ''' ''' <param name="matrix"> ''' An optional <see cref="GlyphOutlineMatrix2"/> used to transform the glyph outline. ''' <para></para> ''' If no value is provided or default structure is passed, an identity matrix ''' will be used (see: <see cref="GlyphOutlineMatrix2.GetIdentityMatrix()"/>), ''' where the transfromed graphical object is identical to the source object. ''' </param> ''' ''' <returns> ''' A <see cref="Byte"/> array containing the raw glyph outline data with the requested <paramref name="format"/>. ''' <para></para> ''' Returns <see langword="Nothing"/> if the glyph is empty in the specified font. ''' </returns> ''' ''' <exception cref="FileNotFoundException"> ''' Thrown when the font file is not found. ''' </exception> <DebuggerStepThrough> Public Shared Function GetFontGlyphOutlineData(fontFile As String, ch As Char, format As GetGlyphOutlineFormat, Optional matrix As GlyphOutlineMatrix2 = Nothing) As Byte() If Not File. Exists(fontFile ) Then Throw New FileNotFoundException("Font file not found.", fileName:=fontFile) End If Using pfc As New PrivateFontCollection() pfc.AddFontFile(fontFile) Using f As New Font(pfc.Families(0), emSize:=1) Return FontExtensions.GetGlyphOutlineData(f, ch, format, matrix) End Using End Using End Function ''' <summary> ''' Determines whether the glyph outline for the specified character is identical in two font files. ''' </summary> ''' ''' <param name="firstFontFile"> ''' Path to the first font file to compare. ''' </param> ''' ''' <param name="secondFontFile"> ''' Path to the second font file to compare. ''' </param> ''' ''' <param name="ch"> ''' The character whose glyph outline will be compared between the two fonts. ''' </param> ''' ''' <returns> ''' <see langword="True"/> if both fonts produce identical outlines for the specified glyph. ''' <para></para> ''' <see langword="False"/> if the outlines differ or if one of the fonts has an empty glyph. ''' If the glyph outlines are empty in both fonts, returns <see langword="True"/>. ''' </returns> ''' ''' <exception cref="FileNotFoundException"> ''' Thrown when one of the font files is not found. ''' </exception> <DebuggerStepThrough> Public Shared Function FontGlyphOutlinesAreEqual(firstFontFile As String, secondFontFile As String, ch As Char) As Boolean If Not File. Exists(firstFontFile ) Then Throw New FileNotFoundException("First font file not found.", fileName:=firstFontFile) End If If Not File. Exists(secondFontFile ) Then Throw New FileNotFoundException("Second ont file not found.", fileName:=secondFontFile) End If Using firstPfc As New PrivateFontCollection(), secondPfc As New PrivateFontCollection() firstPfc.AddFontFile(firstFontFile) secondPfc.AddFontFile(secondFontFile) Using firstFont As New Font(firstPfc.Families(0), emSize:=1), secondFont As New Font(secondPfc.Families(0), emSize:=1) Return FontExtensions.GlyphOutlineIsEqualTo(firstFont, secondFont, ch) End Using End Using End Function ''' <summary> ''' Computes a similarity score between the glyph outline for the specified character in two font files. ''' </summary> ''' ''' <param name="firstFontFile"> ''' Path to the first font file to compare. ''' </param> ''' ''' <param name="secondFontFile"> ''' Path to the second font file to compare. ''' </param> ''' ''' <param name="ch"> ''' The character whose glyph outline will be compared between the two fonts. ''' </param> ''' ''' <returns> ''' A <see cref="Single"/> value between 0.0 and 1.0 representing the similarity ''' (the number of matching bytes in the outline data) of the glyph outlines. ''' <para></para> ''' If one of the fonts has an empty glyph, returns 0. If the glyph outlines are empty in both fonts, returns 1. ''' </returns> ''' ''' <exception cref="FileNotFoundException"> ''' Thrown when one of the font files is not found. ''' </exception> <DebuggerStepThrough> Public Shared Function GetFontGlyphOutlineSimilarity(firstFontFile As String, secondFontFile As String, ch As Char) As Single If Not File. Exists(firstFontFile ) Then Throw New FileNotFoundException("First font file not found.", fileName:=firstFontFile) End If If Not File. Exists(secondFontFile ) Then Throw New FileNotFoundException("Second ont file not found.", fileName:=secondFontFile) End If Using firstPfc As New PrivateFontCollection(), secondPfc As New PrivateFontCollection() firstPfc.AddFontFile(firstFontFile) secondPfc.AddFontFile(secondFontFile) Using firstFont As New Font(firstPfc.Families(0), emSize:=1), secondFont As New Font(secondPfc.Families(0), emSize:=1) Return FontExtensions.GetGlyphOutlineSimilarity(firstFont, secondFont, ch) End Using End Using End Function End Class
y: Module FontExtensions ''' <summary> ''' Retrieves the raw outline data for a given glyph from the specified <see cref="System.Drawing.Font"/>. ''' <para></para> ''' This function calls <see cref="DevCase.Win32.NativeMethods.GetGlyphOutline"/> in background ''' to retrieve outline data with the requested <paramref name="format"/>. ''' </summary> ''' ''' <param name="font"> ''' The <see cref="System.Drawing.Font"/> object from which the glyph will be obtained. ''' </param> ''' ''' <param name="ch"> ''' The character whose glyph outline will be requested. ''' </param> ''' ''' <param name="format"> ''' The format in which the glyph outline will be retrieved. ''' <para></para> ''' This value only can be <see cref="GetGlyphOutlineFormat.Native"/> or <see cref="GetGlyphOutlineFormat.Bezier"/>. ''' <para></para> ''' Note: callers must interpret the returned byte array based on the selected format. ''' </param> ''' ''' <param name="matrix"> ''' An optional <see cref="GlyphOutlineMatrix2"/> used to transform the glyph outline. ''' <para></para> ''' If no value is provided or default structure is passed, an identity matrix ''' will be used (see: <see cref="GlyphOutlineMatrix2.GetIdentityMatrix()"/>), ''' where the transfromed graphical object is identical to the source object. ''' </param> ''' ''' <returns> ''' A <see cref="Byte"/> array containing the raw glyph outline data with the requested <paramref name="format"/>. ''' <para></para> ''' Returns <see langword="Nothing"/> if the glyph is empty in the specified <paramref name="font"/>. ''' </returns> ''' ''' <exception cref="ArgumentNullException"> ''' Thrown when <paramref name="font"/> is <see langword="Nothing"/>. ''' </exception> ''' ''' <exception cref="ArgumentException"> ''' Thrown when the specified <paramref name="format"/> is invalid to request glyph outline data. ''' </exception> ''' ''' <exception cref="System.ComponentModel.Win32Exception"> ''' Thrown when a Win32 error occurs during font or device context operations. ''' </exception> <Extension> <EditorBrowsable(EditorBrowsableState.Always)> <DebuggerStepThrough> Public Function GetGlyphOutlineData(font As Font, ch As Char, format As GetGlyphOutlineFormat, Optional matrix As GlyphOutlineMatrix2 = Nothing) As Byte() If font Is Nothing Then Throw New ArgumentNullException(paramName:=NameOf(font)) End If If format <> GetGlyphOutlineFormat.Native AndAlso format <> GetGlyphOutlineFormat.Bezier Then Dim msg As String = $"The specified format '{format}' does not produce glyph outline data. " & Environment.NewLine & $"Use '{NameOf(GetGlyphOutlineFormat.Native)}' or '{NameOf(GetGlyphOutlineFormat.Bezier)}' " & "formats to request glyph outline data." Throw New ArgumentException(msg, paramName:=NameOf(format)) End If Dim hdc As IntPtr Dim hFont As IntPtr Dim oldObj As IntPtr Dim win32Err As Integer Try hFont = font.ToHfont() hdc = NativeMethods.CreateCompatibleDC(IntPtr.Zero) oldObj = NativeMethods.SelectObject(hdc, hFont) win32Err = Marshal.GetLastWin32Error() If oldObj = IntPtr.Zero OrElse oldObj = DevCase.Win32.Common.Constants.HGDI_ERROR Then Throw New Win32Exception(win32Err) End If Dim chCode As UInteger = CUInt(Convert.ToInt32(ch)) If matrix.Equals(New GlyphOutlineMatrix2()) Then matrix = GlyphOutlineMatrix2.GetIdentityMatrix() End If Dim needed As UInteger = NativeMethods.GetGlyphOutline(hdc, chCode, format, Nothing, Nothing, Nothing, matrix) win32Err = Marshal.GetLastWin32Error() Select Case needed Case 0UI ' Zero curve data points were returned, meaning the glyph is empty. Return Nothing Case DevCase.Win32.Common.Constants.GDI_ERROR If win32Err = Win32ErrorCode.ERROR_SUCCESS Then ' The function returned GDI_ERROR, but no error recorded by GetLastError, meaning the function succeeded. ' Tests carried out have shown that when this happens the glyph simply does not exists. Return Nothing Else Throw New Win32Exception(win32Err) End If Case Else Dim bufferPtr As IntPtr = Marshal.AllocHGlobal(New IntPtr(needed)) Try Dim got As UInteger = NativeMethods.GetGlyphOutline(hdc, chCode, format, Nothing, needed, bufferPtr, matrix) win32Err = Marshal.GetLastWin32Error() If got = DevCase.Win32.Common.Constants.GDI_ERROR AndAlso win32Err <> Win32ErrorCode.ERROR_SUCCESS Then Throw New Win32Exception(win32Err) End If Dim result(CInt(got) - 1) As Byte Marshal.Copy(bufferPtr, result, 0, CInt(got)) Return result Finally Marshal.FreeHGlobal(bufferPtr) End Try End Select Finally If hFont <> IntPtr.Zero Then NativeMethods.DeleteObject(hFont) End If If oldObj <> IntPtr.Zero Then NativeMethods.DeleteObject(oldObj) End If If hdc <> IntPtr.Zero Then NativeMethods.DeleteDC(hdc) End If End Try End Function ''' <summary> ''' Determines whether the glyph outline for the specified character in the source <see cref="System.Drawing.Font"/> ''' is identical to the glyph outline of the same character in another <see cref="System.Drawing.Font"/>. ''' </summary> ''' ''' <param name="firstFont"> ''' The first <see cref="System.Drawing.Font"/> to compare. ''' </param> ''' ''' <param name="secondFont"> ''' The second <see cref="System.Drawing.Font"/> to compare. ''' </param> ''' ''' <param name="ch"> ''' The character whose glyph outline will be compared between the two fonts. ''' </param> ''' ''' <returns> ''' <see langword="True"/> if both fonts produce identical outlines for the specified glyph. ''' <para></para> ''' <see langword="False"/> if the outlines differ or if one of the fonts has an empty glyph. ''' If the glyph outlines are empty in both fonts, returns <see langword="True"/>. ''' </returns> <Extension> <EditorBrowsable(EditorBrowsableState.Always)> <DebuggerStepThrough> Public Function GlyphOutlinesAreEqual(firstFont As Font, secondFont As Font, ch As Char) As Boolean Dim firstBytes As Byte() = FontExtensions.GetGlyphOutlineData(firstFont, ch, GetGlyphOutlineFormat.Native) Dim secondBytes As Byte() = FontExtensions.GetGlyphOutlineData(secondFont, ch, GetGlyphOutlineFormat.Native) Return (firstBytes Is Nothing AndAlso secondBytes Is Nothing) OrElse ( (firstBytes Is Nothing = (secondBytes Is Nothing)) AndAlso firstBytes.SequenceEqual(secondBytes) ) End Function ''' <summary> ''' Computes a similarity score between the glyph outline for the ''' specified character in the source <see cref="System.Drawing.Font"/>, ''' and the the glyph outline of the same character in another <see cref="System.Drawing.Font"/>. ''' </summary> ''' ''' <param name="firstFont"> ''' The first <see cref="System.Drawing.Font"/> to compare. ''' </param> ''' ''' <param name="secondFont"> ''' The second <see cref="System.Drawing.Font"/> to compare. ''' </param> ''' ''' <param name="ch"> ''' The character whose glyph outlines will be compared between the two fonts. ''' </param> ''' ''' <returns> ''' A <see cref="Single"/> value between 0.0 and 1.0 representing the similarity ''' (the number of matching bytes in the outline data) of the glyph outlines. ''' <para></para> ''' If one of the fonts has an empty glyph, returns 0. If the glyph outlines are empty in both fonts, returns 1. ''' </returns> <Extension> <EditorBrowsable(EditorBrowsableState.Always)> <DebuggerStepThrough> Public Function GetGlyphOutlineSimilarity(firstFont As Font, secondFont As Font, ch As Char) As Single Dim firstBytes As Byte() = FontExtensions.GetGlyphOutlineData(firstFont, ch, GetGlyphOutlineFormat.Native) Dim secondBytes As Byte() = FontExtensions.GetGlyphOutlineData(secondFont, ch, GetGlyphOutlineFormat.Native) If firstBytes Is Nothing AndAlso secondBytes Is Nothing Then Return 1.0F End If If (firstBytes Is Nothing) <> (secondBytes Is Nothing) Then Return 0.0F End If Dim maxLength As Integer = System.Math.Max(firstBytes.Length, secondBytes.Length) Dim minLength As Integer = System.Math.Min(firstBytes.Length, secondBytes.Length) Dim equalCount As Integer = 0 For i As Integer = 0 To minLength - 1 If firstBytes(i) = secondBytes(i) Then equalCount += 1 End If Next Return CSng(equalCount) / maxLength End Function 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 fuenteImports necesariosImports System.ComponentModel Imports System.Drawing Imports System.Drawing.Text Imports System.IO Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices Imports DevCase.Win32 Imports DevCase.Win32.Enums 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.)#Region " Constants " Namespace DevCase.Win32.Common.Constants <HideModuleName> Friend Module Constants #Region " GDI32 " ''' <summary> ''' Error return value for some GDI32 functions. ''' </summary> Public Const GDI_ERROR As UInteger = &HFFFFFFFFUI ''' <summary> ''' Error return value for some GDI32 functions. ''' </summary> Public ReadOnly HGDI_ERROR As New IntPtr(-1) #End Region End Module End Namespace #End Region
#Region " Enums " Namespace DevCase.Win32.Enums ''' <remarks> ''' List of System Error Codes: <see href="https://docs.microsoft.com/en-us/windows/desktop/Debug/system-error-codes"/>. ''' </remarks> Public Enum Win32ErrorCode As Integer ''' <summary> ''' The operation completed successfully. ''' </summary> ERROR_SUCCESS = &H0 End Enum ''' <remarks> ''' <see href="https://learn.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-wcrange"/> ''' </remarks> <Flags> Public Enum GetGlyphIndicesFlags ' GGI ''' <summary> ''' Marks unsupported glyphs with the hexadecimal value 0xFFFF. ''' </summary> MarkNonExistingGlyphs = 1 ' GGI_MARK_NONEXISTING_GLYPHS End Enum ''' <remarks> ''' <see href="https://learn.microsoft.com/en-us/windows/win32/api/wingdi/nf-wingdi-getglyphoutlinew"/> ''' </remarks> Public Enum GetGlyphOutlineFormat ' GGO Metrics = 0 Bitmap = 1 ''' <summary> ''' The function retrieves the curve data points in the rasterizer's native format and uses the font's design units. ''' </summary> Native = 2 Bezier = 3 BitmapGray2 = 4 BitmapGray4 = 5 BitmapGray8 = 6 GlyphIndex = &H80 Unhinted = &H100 End Enum End Namespace #End Region
#Region " Structures " Namespace DevCase.Win32.Structures #Region " GlyphMetrics " ''' <remarks> ''' <see href="https://learn.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-glyphmetrics"/> ''' </remarks> <StructLayout(LayoutKind.Sequential)> Public Structure GlyphMetrics Public BlackBoxX As UInteger Public BlackBoxY As UInteger Public GlyphOrigin As NativePoint Public CellIncX As Short Public CellIncY As Short End Structure #End Region #Region " NativePoint (POINT) " ''' <summary> ''' Defines the x- and y- coordinates of a point. ''' </summary> ''' ''' <remarks> ''' <see href="https://msdn.microsoft.com/en-us/library/windows/desktop/dd162805%28v=vs.85%29.aspx"/> ''' </remarks> <DebuggerStepThrough> <StructLayout(LayoutKind.Sequential)> Public Structure NativePoint #Region " Fields " Public X As Integer Public Y As Integer #End Region #Region " Constructors " Public Sub New(x As Integer, y As Integer) Me.X = x Me.Y = y End Sub Public Sub New(pt As Point) Me.New(pt.X, pt.Y) End Sub #End Region #Region " Operator Conversions " Public Shared Widening Operator CType(pt As NativePoint) As Point Return New Point(pt.X, pt.Y) End Operator Public Shared Widening Operator CType(pt As Point) As NativePoint Return New NativePoint(pt.X, pt.Y) End Operator #End Region End Structure #End Region #Region " GlyphOutlineMatrix2 " ''' <remarks> ''' <see href="https://learn.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-mat2"/> ''' </remarks> <StructLayout(LayoutKind.Sequential)> Public Structure GlyphOutlineMatrix2 ' MAT2 Public M11 As Fixed Public M12 As Fixed Public M21 As Fixed Public M22 As Fixed ''' <summary> ''' Gets an <see cref="GlyphOutlineMatrix2"/> transformation in which the transformed graphical object is identical to the source object. ''' This is called an identity matrix. ''' <para></para> ''' In this identity matrix, ''' the value of <see cref="GlyphOutlineMatrix2.M11"/> is 1, ''' the value of <see cref="GlyphOutlineMatrix2.M12"/> is zero, ''' the value of <see cref="GlyphOutlineMatrix2.M21"/> is zero, ''' and the value of <see cref="GlyphOutlineMatrix2.M22"/> is 1. ''' </summary> ''' ''' <returns> ''' The resulting <see cref="GlyphOutlineMatrix2"/>. ''' </returns> Public Shared Function GetIdentityMatrix() As GlyphOutlineMatrix2 Return New GlyphOutlineMatrix2() With { .M11 = New Fixed With {.Value = 1}, .M22 = New Fixed With {.Value = 1} } End Function End Structure #End Region #Region " Fixed " ''' <summary> ''' Contains the integral and fractional parts of a fixed-point real number. ''' <para></para> ''' Note: The <see cref="Fixed"/> structure is used to describe the elements of the <see cref="GlyphOutlineMatrix2"/> structure. ''' </summary> ''' ''' <remarks> ''' <see href="https://docs.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-fixed"/> ''' </remarks> <StructLayout(LayoutKind.Sequential)> Public Structure Fixed #Region " Public Fields " ''' <summary> ''' The fractional value. ''' </summary> Public Fraction As UShort ''' <summary> ''' The integral value. ''' </summary> Public Value As Short #End Region #Region " Operator Conversions " Public Shared Widening Operator CType(f As Fixed) As Decimal Return Decimal.Parse($"{f.Value.ToString(NumberFormatInfo.InvariantInfo)}{NumberFormatInfo.InvariantInfo.NumberDecimalSeparator}{f.Fraction.ToString(NumberFormatInfo.InvariantInfo)}", NumberFormatInfo.InvariantInfo) End Operator Public Shared Widening Operator CType(dec As Decimal) As Fixed Return New Fixed With { .Value = CShort(System.Math.Truncate(System.Math.Truncate(dec))), .Fraction = UShort.Parse(dec.ToString(NumberFormatInfo.InvariantInfo).Split({NumberFormatInfo.InvariantInfo.NumberDecimalSeparator}, StringSplitOptions.None)(1), NumberFormatInfo.InvariantInfo) } End Operator #End Region #Region " Public Methods " Public Overrides Function ToString() As String Return CDec(Me).ToString() End Function #End Region End Structure #End Region End Namespace #End Region
#Region " NativeMethods " Namespace DevCase.Win32.NativeMethods <SuppressUnmanagedCodeSecurity> Friend Module Gdi32 ''' <summary> ''' Creates a memory device context (DC) compatible with the specified device. ''' </summary> ''' ''' <remarks> ''' <see href="https://msdn.microsoft.com/en-us/library/windows/desktop/dd183489%28v=vs.85%29.aspx"/> ''' </remarks> <DllImport("gdi32.dll", SetLastError:=True)> Public Function CreateCompatibleDC(hdc As IntPtr ) As IntPtr End Function ''' <summary> ''' Deletes the specified device context (DC). ''' <para></para> ''' An application must not delete a DC whose handle was obtained by calling the <see cref="GetDC"/> function. ''' instead, it must call the <see cref="ReleaseDC"/> function to free the DC. ''' </summary> ''' ''' <remarks> ''' <see href="https://msdn.microsoft.com/en-us/library/windows/desktop/dd183533%28v=vs.85%29.aspx"/> ''' </remarks> <DllImport("gdi32.dll")> Public Function DeleteDC(hdc As IntPtr ) As <MarshalAs(UnmanagedType.Bool)> Boolean End Function ''' <summary> ''' Selects an object into a specified device context. ''' <para></para> ''' The new object replaces the previous object of the same type. ''' </summary> ''' ''' <remarks> ''' <see href="https://msdn.microsoft.com/en-us/library/windows/desktop/dd162957%28v=vs.85%29.aspx"/> ''' </remarks> <DllImport("gdi32.dll", ExactSpelling:=False)> Public Function SelectObject(hdc As IntPtr, hObject As IntPtr ) As IntPtr End Function ''' <summary> ''' Deletes a logical pen, brush, font, bitmap, region, or palette, ''' freeing all system resources associated with the object. ''' <para></para> ''' After the object is deleted, the specified handle is no longer valid. ''' <para></para> ''' Do not delete a drawing object (pen or brush) while it is still selected into a DC. ''' <para></para> ''' When a pattern brush is deleted, the bitmap associated with the brush is not deleted. ''' The bitmap must be deleted independently. ''' </summary> ''' ''' <remarks> ''' <see href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms633540%28v=vs.85%29.aspx"/> ''' </remarks> <DllImport("gdi32.dll", ExactSpelling:=False, SetLastError:=True)> Public Function DeleteObject(hObject As IntPtr ) As <MarshalAs(UnmanagedType.Bool)> Boolean End Function ''' <summary> ''' Translates a string into an array of glyph indices. ''' <para></para> ''' The function can be used to determine whether a glyph exists in a font. ''' </summary> ''' ''' <remarks> ''' <see href="https://learn.microsoft.com/en-us/windows/win32/api/wingdi/nf-wingdi-getglyphindicesw"/> ''' </remarks> <DllImport("gdi32.dll", SetLastError:=False, CharSet:=CharSet.Auto, BestFitMapping:=False, ThrowOnUnmappableChar:=True)> Public Function GetGlyphIndices(hdc As IntPtr, str As String, strLen As Integer, <[Out], MarshalAs(UnmanagedType.LPArray, SizeParamIndex:=2)> glyphIndices As UShort(), Optional flags As GetGlyphIndicesFlags = GetGlyphIndicesFlags.MarkNonExistingGlyphs ) As UInteger End Function ''' <summary> ''' Retrieves the outline or bitmap for a character in the TrueType font that is selected into the specified device context. ''' </summary> ''' ''' <remarks> ''' <see href="https://learn.microsoft.com/en-us/windows/win32/api/wingdi/nf-wingdi-getglyphoutlinew"/> ''' </remarks> <DllImport("gdi32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> Public Function GetGlyphOutline(hdc As IntPtr, ch As UInteger, format As GetGlyphOutlineFormat, <Out> ByRef refMetrics As GlyphMetrics, bufferSize As UInteger, buffer As IntPtr, ByRef refMatrix2 As GlyphOutlineMatrix2 ) As UInteger End Function End Module End Namespace #End Region
Clase principal 'UtilFonts' y modulo 'FontExtensions', que contienen los métodos universales en torno a fuentes de textoPublic Class UtilFonts ''' <summary> ''' Prevents a default instance of the <see cref="UtilFonts"/> class from being created. ''' </summary> Private Sub New() End Sub ''' <summary> ''' Determines whether a glyph exists in the given font file ''' for the specified character. ''' </summary> ''' ''' <param name="fontFile"> ''' Path to the font file used to check for glyph availability. ''' </param> ''' ''' <param name="ch"> ''' The character that represents the glyph to check. ''' </param> ''' ''' <returns> ''' <see langword="True"/> if a glyph exists in the font for the specified character; ''' otherwise, <see langword="False"/>. ''' </returns> <DebuggerStepThrough> Public Shared Function FontHasGlyph(fontFile As String, ch As Char) As Boolean Return UtilFonts.FontHasGlyphs(fontFile, ch) = 1 End Function ''' <summary> ''' Determines whether a glyph exists in the given font file ''' for all the characters in the speciied string. ''' </summary> ''' ''' <param name="fontFile"> ''' Path to the font file used to check for glyphs availability. ''' </param> ''' ''' <param name="str"> ''' A <see cref="String"/> with the character(s) that represents the glyphs to check. ''' <para></para> ''' Each character (or surrogate pair) is checked for a existing glyph in the font. ''' </param> ''' ''' <returns> ''' The count of characters from <paramref name="str"/> parameter that have a existing glyph in the font. ''' <para></para> ''' 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. ''' </returns> ''' ''' <exception cref="FileNotFoundException"> ''' Thrown when the font file is not found. ''' </exception> <DebuggerStepThrough> Public Shared Function FontHasGlyphs(fontFile As String, str As String) As UInteger If Not System. IO. File. Exists(fontFile ) Then Throw New FileNotFoundException("Font file not found.", fileName:=fontFile) End If Using pfc As New PrivateFontCollection() pfc.AddFontFile(fontFile) Using f As New Font(pfc.Families(0), emSize:=1) Return FontExtensions.HasGlyphs(f, str) End Using End Using End Function ''' <summary> ''' Determines whether a glyph for the specified character in the given font file has an outline. ''' <para></para> ''' This is useful to determine whether the glyph is empty (no character is drawn), ''' but note that a glyph with outlines does not necessarily mean that the character is fully represented. ''' Some fonts, for instance, only renders diacritical marks for accented vowels ''' instead the full letter (e.g., "<b>´</b>" instead of "<b>í</b>"). ''' This function solely determines whether the glyph draws an outline, nothing more. ''' <para></para> ''' To determine whether a glyph exists in the given font file for the specified character, use ''' <see cref="UtilFonts.FontHasGlyph"/> or <see cref="UtilFonts.FontHasGlyphs"/> instead. ''' </summary> ''' ''' <param name="fontFile"> ''' Path to the font file used to check for glyph availability. ''' </param> ''' ''' <param name="ch"> ''' The character that represents the glyph to check in the font. ''' </param> ''' ''' <returns> ''' Returns <see langword="True"/> if the glyph has an outline (visible shape data exists). ''' <para></para> ''' Returns <see langword="False"/> if the glyph does not have an outline, ''' meaning the glyph is empty/unsupported by the font. ''' </returns> ''' ''' <exception cref="FileNotFoundException"> ''' Thrown when the font file is not found. ''' </exception> <DebuggerStepThrough> Public Shared Function FontGlyphHasOutline(fontFile As String, ch As Char) As Boolean If Not System. IO. File. Exists(fontFile ) Then Throw New FileNotFoundException("Font file not found.", fileName:=fontFile) End If Using pfc As New PrivateFontCollection() pfc.AddFontFile(fontFile) Using f As New Font(pfc.Families(0), emSize:=1) Return FontExtensions.GlyphHasOutline(f, ch) End Using End Using End Function End Class
Module FontExtensions ''' <summary> ''' Determines whether a glyph exists in the given <see cref="System.Drawing.Font"/> ''' for the specified character. ''' </summary> ''' ''' <param name="font"> ''' The <see cref="System.Drawing.Font"/> used to check for glyph availability. ''' </param> ''' ''' <param name="ch"> ''' The character that represents the glyph to check. ''' </param> ''' ''' <returns> ''' <see langword="True"/> if a glyph exists in the font for the specified character; ''' otherwise, <see langword="False"/>. ''' </returns> <Extension> <EditorBrowsable(EditorBrowsableState.Always)> <DebuggerStepThrough> Public Function HasGlyph(font As Font, ch As Char) As Boolean Return FontExtensions.HasGlyphs(font, ch) = 1 End Function ''' <summary> ''' Determines whether a glyph exists in the given <see cref="System.Drawing.Font"/> ''' for all the characters in the speciied string. ''' </summary> ''' ''' <param name="font"> ''' The <see cref="System.Drawing.Font"/> used to check for glyphs availability. ''' </param> ''' ''' <param name="str"> ''' A <see cref="String"/> with the character(s) that represents the glyphs to check. ''' <para></para> ''' Each character (or surrogate pair) is checked for a existing glyph in the font. ''' </param> ''' ''' <returns> ''' The count of characters from <paramref name="str"/> parameter that have a existing glyph in the font. ''' <para></para> ''' 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. ''' </returns> ''' ''' <exception cref="ArgumentNullException"> ''' Thrown when <paramref name="font"/> or <paramref name="str"/> are null. ''' </exception> ''' ''' <exception cref="Win32Exception"> ''' Thrown when a call to Windows API GDI32 functions (creating device context, selecting font, or retrieving glyph indices) fails. ''' </exception> <Extension> <EditorBrowsable(EditorBrowsableState.Always)> <DebuggerStepThrough> Public Function HasGlyphs(font As Font, str As String) As UInteger If font Is Nothing Then Throw New ArgumentNullException(paramName:=NameOf(font)) End If If String.IsNullOrEmpty(str) Then Throw New ArgumentNullException(paramName:=NameOf(str)) End If Dim hdc As IntPtr Dim hFont As IntPtr Dim oldObj As IntPtr Dim win32Err As Integer Try hFont = font.ToHfont() hdc = NativeMethods.CreateCompatibleDC(IntPtr.Zero) win32Err = Marshal.GetLastWin32Error() If hdc = IntPtr.Zero Then Throw New Win32Exception(win32Err) End If oldObj = NativeMethods.SelectObject(hdc, hFont) win32Err = Marshal.GetLastWin32Error() If oldObj = IntPtr.Zero OrElse oldObj = DevCase.Win32.Common.Constants.HGDI_ERROR Then Throw New Win32Exception(win32Err) End If ' Reserve output for each text unit (can be 1 or 2 chars if it's a surrogate pair). Dim strLen As Integer = str.Length Dim indices As UShort() = New UShort(strLen - 1) {} ' Get the glyph indices for the string in the given device context. Dim converted As UInteger = NativeMethods.GetGlyphIndices(hdc, str, strLen, indices, GetGlyphIndicesFlags.MarkNonExistingGlyphs) win32Err = Marshal.GetLastWin32Error() If converted = DevCase.Win32.Common.Constants.GDI_ERROR Then Throw New Win32Exception(win32Err) End If ' Count glyphs that exist (index <> 0xFFFF). ' If any glyph index is 0xFFFF, the glyph does not exist in that font. Dim count As UInteger For Each index As UShort In indices If index <> &HFFFFUS Then count += 1UI End If Next Return count Finally If oldObj <> IntPtr.Zero Then NativeMethods.DeleteObject(oldObj) End If If hFont <> IntPtr.Zero Then NativeMethods.DeleteObject(hFont) End If If hdc <> IntPtr.Zero Then NativeMethods.DeleteDC(hdc) End If End Try End Function ''' <summary> ''' Determines whether a glyph for the specified character in the given <see cref="System.Drawing.Font"/> has an outline. ''' <para></para> ''' This is useful to determine whether the glyph is empty (no character is drawn), ''' but note that a glyph with outlines does not necessarily mean that the character is fully represented. ''' Some fonts, for instance, only renders diacritical marks for accented vowels ''' instead the full letter (e.g., "<b>´</b>" instead of "<b>í</b>"). ''' This function solely determines whether the glyph draws an outline, nothing more. ''' <para></para> ''' To determine whether a glyph exists in the given font file for the specified character, use ''' <see cref="FontExtensions.HasGlyph"/> or <see cref="FontExtensions.HasGlyphs"/> instead. ''' </summary> ''' ''' <param name="font"> ''' The <see cref="System.Drawing.Font"/> used to check for glyph availability. ''' </param> ''' ''' <param name="ch"> ''' The character that represents the glyph to check in the font. ''' </param> ''' ''' <returns> ''' Returns <see langword="True"/> if the glyph has an outline (visible shape data exists). ''' <para></para> ''' Returns <see langword="False"/> if the glyph does not have an outline, ''' meaning the glyph is empty/unsupported by the font. ''' </returns> <Extension> <EditorBrowsable(EditorBrowsableState.Always)> <DebuggerStepThrough> Public Function GlyphHasOutline(font As Font, ch As Char) As Boolean If font Is Nothing Then Throw New ArgumentNullException(paramName:=NameOf(font)) End If Dim hdc As IntPtr Dim hFont As IntPtr Dim oldObj As IntPtr Dim win32Err As Integer Try hFont = font.ToHfont() hdc = NativeMethods.CreateCompatibleDC(IntPtr.Zero) oldObj = NativeMethods.SelectObject(hdc, hFont) win32Err = Marshal.GetLastWin32Error() If oldObj = IntPtr.Zero OrElse oldObj = DevCase.Win32.Common.Constants.HGDI_ERROR Then Throw New Win32Exception(win32Err) End If Dim chCode As UInteger = CUInt(Convert.ToInt32(ch)) Dim format As GetGlyphOutlineFormat = GetGlyphOutlineFormat.Native Dim matrix As GlyphOutlineMatrix2 = GlyphOutlineMatrix2.GetIdentityMatrix() Dim ptCount As UInteger = NativeMethods.GetGlyphOutline(hdc, chCode, format, Nothing, Nothing, Nothing, matrix) win32Err = Marshal.GetLastWin32Error() Select Case ptCount Case 0UI ' Zero curve data points were returned, meaning the glyph is empty/invisible. Return False Case DevCase.Win32.Common.Constants.GDI_ERROR If win32Err = Win32ErrorCode.ERROR_SUCCESS Then ' The function returned GDI_ERROR, but no error recorded by GetLastError, meaning the function succeeded. ' Tests carried out have shown that when this happens the glyph simply does not exists. Return False Else Throw New Win32Exception(win32Err) End If Case Else Return True End Select Finally If oldObj <> IntPtr.Zero Then NativeMethods.DeleteObject(oldObj) End If If hFont <> IntPtr.Zero Then NativeMethods.DeleteObject(hFont) End If If hdc <> IntPtr.Zero Then NativeMethods.DeleteDC(hdc) End If End Try ' =================================================== ' ALTERNATIVE METHODOLOGY USING PURE MANAGED GDI+ ' ' (results are the same than using Windows API calls) ' =================================================== ' ' 'If font Is Nothing Then ' Throw New ArgumentNullException(paramName:=NameOf(font)) 'End If ' 'If font.Unit = GraphicsUnit.Pixel AndAlso font.Size < 8 Then ' Dim msg As String = ' "Font size must be equals or greater than 8 pixels when using GraphicsUnit.Pixel to avoid unreliable pixel detection. " & ' "Suggested font size is 16 pixel size; A value of 32, 64 or bigger pixel size would produce the same results." ' Throw New ArgumentException(msg) ' 'ElseIf font.Size < 4 Then ' Dim msg As String = ' "Font size must be equals or greater than 4 to avoid unreliable pixel detection. " & ' "Suggested usage is GraphicsUnit.Pixel with a font size of 16 pixels; " & ' "A value of 32, 64 or bigger pixel size would produce the same results." ' Throw New ArgumentException(msg) ' 'End If ' '' Measure the required size for the glyph. 'Dim requiredSize As Size 'Using tempBmp As New Bitmap(1, 1) ' Using g As Graphics = Graphics.FromImage(tempBmp) ' Dim sizeF As SizeF = g.MeasureString(ch, font) ' ' Add a small margin to avoid clipping due to rounding. ' requiredSize = New Size(CInt(System.Math.Ceiling(sizeF.Width)) + 4, ' CInt(System.Math.Ceiling(sizeF.Height)) + 4) ' End Using 'End Using ' '' Create a bitmap big enough to render the glyph, '' filling the bitmap background with white color and '' drawing the character in black. 'Using bmp As New Bitmap(requiredSize.Width, requiredSize.Height), ' g As Graphics = Graphics.FromImage(bmp) ' ' Using AntiAlias may help ensure that very thin glyph strokes ' ' still produce detectable pixels, with gray edges. ' ' Without anti-aliasing, such strokes might render too faint or disappear entirely, ' ' causing the glyph to be misidentified as empty. ' g.TextRenderingHint = Drawing.Text.TextRenderingHint.AntiAlias ' g.Clear(Color.White) ' g.DrawString(ch, font, Brushes.Black, 0, 0) ' ' Dim rect As New Rectangle(0, 0, bmp.Width, bmp.Height) ' Dim bmpData As BitmapData = bmp.LockBits(rect, Imaging.ImageLockMode.ReadOnly, Imaging.PixelFormat.Format32bppArgb) ' ' Try ' Dim ptr As IntPtr = bmpData.Scan0 ' Dim bytes As Integer = System.Math.Abs(bmpData.Stride) * bmp.Height ' Dim pixelValues(bytes - 1) As Byte ' Marshal.Copy(ptr, pixelValues, 0, bytes) ' ' ' Iterate through each pixel. ' ' PixelFormat.Format32bppArgb stores pixels as [Blue][Green][Red][Alpha] ' ' i=Blue, i+1=Green, i+2=Red, i+3=Alpha ' For i As Integer = 0 To pixelValues.Length - 1 Step 4 ' Dim red As Byte = pixelValues(i + 2) ' ' ' Check if the pixel is darker than nearly-white (threshold 250) ' ' If so, we found a visible pixel, meaning the glyph is drawn. ' If red < 250 Then ' Return True ' End If ' Next ' Finally ' bmp.UnlockBits(bmpData) ' ' End Try 'End Using ' '' No visible pixels found, meaning the glyph is empty/unsupported by the font. 'Return False End Function End Module
◉ Modo de empleoEl 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). Dim fontFiles As IEnumerable(Of String) = Directory.EnumerateFiles("C:\Fonts", "*.ttf", SearchOption.TopDirectoryOnly) Dim fontsToDelete As New HashSet(Of String)() Dim chars As Char() = "áéíóú".ToCharArray() For Each fontFile As String In fontFiles Dim missingChars As New HashSet(Of Char)() For Each ch As Char In chars If Not UtilFonts.FontHasGlyph(fontFile, ch) OrElse Not UtilFonts.FontGlyphHasOutline(fontFile, ch) Then missingChars.Add(ch) End If Next If missingChars.Count > 0 Then Console.WriteLine($"[{Path.GetFileName(fontFile)}] Missing glyphs: {String.Join(", ", missingChars)}") fontsToDelete.Add(fontFile) End If Next For Each fontFile As String In fontsToDelete ' Console.WriteLine($"Deleting font file: {fontFile}") ' Microsoft.VisualBasic.FileIO.FileSystem.DeleteFile(fontFile, FileIO.UIOption.OnlyErrorDialogs, FileIO.RecycleOption.SendToRecycleBin) 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. 👋
|
|
|
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.  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... ''' <summary> ''' Retrieves the resource name of a TrueType (.ttf) or OpenType font file (.otf) ''' by creating a temporary scalable font resource file and reading its contents. ''' <para></para> ''' This name may differ from the value of the following properties: ''' <list type="bullet"> ''' <item><description><see cref="System.Drawing.Font.Name"/>.</description></item> ''' <item><description><see cref="System.Drawing.Font.OriginalFontName"/>.</description></item> ''' <item><description><see cref="System.Drawing.Font.SystemFontName"/>.</description></item> ''' <item><description><see cref="System.Windows.Media.GlyphTypeface.FamilyNames"/>.</description></item> ''' <item><description><see cref="System.Windows.Media.GlyphTypeface.Win32FamilyNames"/>.</description></item> ''' </list> ''' </summary> ''' ''' <param name="fontFile"> ''' The path to the font file (e.g., <b>"C:\font.ttf"</b>). ''' </param> ''' ''' <returns> ''' The resource name of the given font file. ''' </returns> <DebuggerStepThrough> Public Shared Function GetFontResourceName(fontFile As String) As String If Not File. Exists(fontFile ) Then Dim msg As String = $"The font file does not exist: '{fontFile}'" Throw New FileNotFoundException(msg, fontFile) End If Dim fontName As String = Nothing Dim tempFile As String = Path.Combine(Path.GetTempPath(), "~FONT.RES") ' Ensure any previous existing temp file is deleted. If File. Exists(tempFile ) Then Try Catch ex As Exception Dim msg As String = $"Cannot delete existing temp resource file: '{tempFile}'" Throw New IOException(msg, ex) End Try End If ' Create a temporary scalable font resource. Dim created As Boolean = NativeMethods.CreateScalableFontResource(1UI, tempFile, fontFile, Nothing) If Not created Then Dim msg As String = "Failed to create scalable font resource." Throw New IOException(msg) End If Try ' Read the temp font file resource into a string. Dim buffer As Byte() = File. ReadAllBytes(tempFile ) Dim bufferStr As String = Encoding.Default.GetString(buffer) ' Look for the "FONTRES:" marker. Const fontResMarker As String = "FONTRES:" Dim pos As Integer = bufferStr.IndexOf(fontResMarker) If pos < 0 Then Dim msg As String = "FONTRES marker not found in temporary font resource file." Throw New InvalidOperationException(msg) End If pos += fontResMarker.Length Dim endPos As Integer = bufferStr.IndexOf(ControlChars.NullChar, pos) If endPos < 0 Then Dim msg As String = "Cannot determine the end position of the font name string in the font resource file content." Throw New InvalidOperationException(msg) End If fontName = bufferStr.Substring(pos, endPos - pos) Catch ex As Exception Throw Finally ' Always attempt to delete the created temporary resource file. Try Catch ' Ignore deletion exceptions; cleanup best effort. End Try End Try Return fontName End Function
#Region " NativeMethods " Namespace DevCase.Win32.NativeMethods <SuppressUnmanagedCodeSecurity> Friend Module User32 #Region " GDI32.dll " <DllImport("GDI32.dll", CharSet:=CharSet.Auto, SetLastError:=True, BestFitMapping:=False, ThrowOnUnmappableChar:=True)> Friend Function CreateScalableFontResource(hidden As UInteger, resourceFile As String, fontFile As String, currentPath As String ) As <MarshalAs(UnmanagedType.Bool)> Boolean End Function #End Region End Module End Namespace #End Region
OFF-TOPICSi 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 fuentesPara 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): 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) Just Breathe Bold ObliqueSeven (OpenType)  ◉ Nombre devuelto por mi función GetFontFriendlyName, con sufijo: 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: Just Breathe Bold ObliqueSeven ◉ Nombre devuelto por mi función GetFontResourceName: (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: El código utilizado: Dim fontUri As New Uri("C:\JustBreatheBoldObliqueseven-7vgw.otf", UriKind.Absolute) Dim gtf As New System.Windows.Media.GlyphTypeface(fontUri) Dim fontName As String = String.Join(" "c, gtf.FamilyNames.Values) Dim fontFaceNames As String = String.Join(" "c, gtf.FaceNames.Values) Dim fullName As String = $"{fontName} {fontFaceNames}" Console.WriteLine(fullName)
◉ Nombre devuelto por las propiedades System.Drawing.Font.Name y System.Drawing.FontFamily.Name: ◉ Nombre devuelto por las propiedades System.Drawing.Font.OriginalName y System.Drawing.Font.SystemNameNINGUNO (VALOR VACÍO EN ESTE CASO CONCRETO) Acerca de fontreg.exeExiste 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:#If NETCOREAPP Then Imports System.Buffers.Binary #End If Imports System.ComponentModel Imports System.Diagnostics.CodeAnalysis Imports System.IO Imports System.Runtime.InteropServices Imports System.Runtime.Versioning Imports System.Security Imports System.ServiceProcess Imports System.Text Imports Microsoft.Win32 Imports Microsoft.WindowsAPICodePack.Shell Imports DevCase.Win32 Imports DevCase.Win32.Enums
Clases secundarias requeridas:#Region " Constants " Namespace DevCase.Win32.Common.Constants <HideModuleName> Friend Module Constants #Region " Window Messaging " ''' <summary> ''' Handle to use with window messaging functions. ''' <para></para> ''' When used, the message is sent to all top-level windows in the system, ''' including disabled or invisible unowned windows, overlapped windows, and pop-up windows; ''' but the message is not sent to child windows. ''' </summary> Friend ReadOnly HWND_BROADCAST As New IntPtr(65535US) #End Region End Module End Namespace #End Region
#Region " Window Messages " Namespace DevCase.Win32.Enums Friend Enum WindowMessages As Integer ''' <summary> ''' An application sends the message to all top-level windows in the system after changing the ''' pool of font resources. ''' </summary> WM_FontChange = &H1D End Enum End Namespace #End Region
#Region " NativeMethods " Namespace DevCase.Win32.NativeMethods <SuppressUnmanagedCodeSecurity> Friend Module Gdi32 <DllImport("GDI32.dll", SetLastError:=False, CharSet:=CharSet.Auto, ThrowOnUnmappableChar:=True, BestFitMapping:=False)> Friend Function AddFontResource(fileName As String ) As Integer End Function <DllImport("GDI32.dll", SetLastError:=True, CharSet:=CharSet.Auto, ThrowOnUnmappableChar:=True, BestFitMapping:=False)> Friend Function RemoveFontResource(fileName As String ) As <MarshalAs(UnmanagedType.Bool)> Boolean End Function End Module <SuppressUnmanagedCodeSecurity> Friend Module User32 <DllImport("User32.dll", SetLastError:=True)> Friend Function SendMessage(hWnd As IntPtr, msg As WindowMessages, wParam As IntPtr, lParam As IntPtr ) As IntPtr End Function End Module End Namespace #End Region
Clase principal 'UtilFonts', que contiene los métodos universales (y otros miembros relacionados) en torno a fuentes de texto:Public Class UtilFonts ''' <summary> ''' Magic number located at the beginning of a TrueType font (.ttf) file header. ''' </summary> Private Shared ReadOnly TT_MAGIC As Byte() = { &H0, &H1, &H0, &H0 } ''' <summary> ''' Magic number located at the beginning of a TrueType font (.ttf) file header ''' that starts with ASCII string "true". ''' </summary> Private Shared ReadOnly TT_MAGIC_TRUE As Byte() = { &H74, &H72, &H75, &H65 ' "true" } ''' <summary> ''' Magic number located at the beginning of an OpenType font with CFF (PostScript) outlines (.otf) file header. ''' <para></para> ''' This distinguishes them from OpenType-TT fonts. ''' </summary> Private Shared ReadOnly OT_MAGIC As Byte() = { &H4F, &H54, &H54, &H4F ' "OTTO" } ''' <summary> ''' Retrieves a user-friendly name for a given font file, ''' that is identical to the 'Title' property shown by Windows Explorer, ''' allowing to provide consistent font identification in your application. ''' </summary> ''' ''' <param name="fontFile"> ''' The path to the font file (e.g., <b>"C:\font.ttf"</b>). ''' </param> ''' ''' <param name="includeSuffix"> ''' If <see langword="True"/>, includes a suffix that specifies ''' the underlying font technology (e.g., "Font name <c>(TrueType)</c>", "Font name <c>(OpenType)</c>"), ''' ensuring that the font name matches exactly the name shown in Microsoft's Windows Font Viewer (FontView.exe) title bar. ''' </param> ''' ''' <returns> ''' The user-friendly name for the given font file. ''' </returns> <DebuggerStepThrough> Public Shared Function GetFontFriendlyName(fontFile As String, includeSuffix As Boolean) As String If Not File. Exists(fontFile ) Then Dim msg As String = $"The font file does not exist: '{fontFile}'" Throw New FileNotFoundException(msg, fontFile) End If Dim fontTitle As String = ShellFile.FromFilePath(fontFile).Properties.System.Title.Value.Trim() If String.IsNullOrWhiteSpace(fontTitle) Then Dim msg As String = "'Title' property for the given font is empty." Throw New FormatException(msg) End If If includeSuffix Then Dim fontType As FontType = UtilFonts.GetFontType(fontFile) Select Case fontType Case FontType.Invalid Dim msg As String = "File does not seems a valid font file (file size is too small)." Throw New FileFormatException(msg) Case FontType.Unknown Dim msg As String = "Font file type is not recognized. " & "It might be an unsupported format, corrupted file Or Not a valid font file." Throw New FileFormatException(msg) Case FontType.TrueType Return $"{fontTitle} (TrueType)" Case FontType.OpenTypeCFF, FontType.OpenTypeTT Return $"{fontTitle} (OpenType)" Case Else ' FontType.Raster ' Nothing to do. End Select End If Return fontTitle End Function ''' <summary> ''' Determines the type of a font file. ''' <para></para> ''' Supports TrueType (.ttf), OpenType (.otf/.ttf) and Raster/Bitmap (.fon). ''' </summary> ''' ''' <param name="fontFile"> ''' The path to the font file (e.g., <b>"C:\font.ttf"</b>). ''' </param> ''' ''' <returns> ''' A <see cref="FontType"/> value indicating the font type of the given file. ''' <para></para> ''' If the font type cannot be recognized, it returns <see cref="FontType.Unknown"/>. ''' <para></para> ''' If the given file does not meet the criteria to be treated as a font file, it returns <see cref="FontType.Invalid"/>. ''' </returns> <DebuggerStepThrough> Public Shared Function GetFontType(fontFile As String) As FontType If Not File. Exists(fontFile ) Then Dim msg As String = $"The font file does not exist: '{fontFile}'" Throw New FileNotFoundException(msg, fontFile) End If ' 512 bytes is the minimum length I found sufficient ' to reliably read the header of any raster (.fon) font file ' to find its string markers that identifies this file type. Const minFontFileLength As Short = 512 Dim fi As New FileInfo(fontFile) If fi.Length <= minFontFileLength Then Return FontType.Invalid End If Try Using fs As FileStream = fi.OpenRead(), br As New BinaryReader(fs) Dim headerBytes As Byte() = br.ReadBytes(4) ' TrueType check. If headerBytes.SequenceEqual(UtilFonts.TT_MAGIC) OrElse headerBytes.SequenceEqual(UtilFonts.TT_MAGIC_TRUE) Then ' OpenType-TT check br.BaseStream.Seek(4, SeekOrigin.Begin) #If NETCOREAPP Then Dim numTables As UShort = BinaryPrimitives.ReverseEndianness(br.ReadUInt16()) #Else ' Read two bytes directly. Dim bytes As Byte() = br.ReadBytes(2) ' If the system is little-endian, reverse the bytes to interpret as big-endian. If BitConverter.IsLittleEndian Then Array.Reverse(bytes) End If ' Now get the UShort value in big-endian. Dim swapped As UShort = BitConverter.ToUInt16(bytes, 0) Dim numTables As UShort = swapped #End If br.BaseStream.Seek(6, SeekOrigin.Current) ' skip: searchRange, entrySelector, rangeShift ' Search advanced OpenType tables. For i As Integer = 0 To numTables - 1 Dim tag As String = Encoding.ASCII.GetString(br.ReadBytes(4)) br.ReadBytes(12) ' checkSum, offset, length If tag = "GSUB" OrElse tag = "GPOS" OrElse tag = "GDEF" OrElse tag = "BASE" Then Return FontType.OpenTypeTT End If Next Return FontType.TrueType End If ' OpenType CFF check. If headerBytes.SequenceEqual(UtilFonts.OT_MAGIC) Then Return FontType.OpenTypeCFF End If ' Raster/Bitmap check. br.BaseStream.Seek(0, SeekOrigin.Begin) headerBytes = br.ReadBytes(minFontFileLength) Dim headerText As String = Encoding.ASCII.GetString(headerBytes) If headerText.Contains("FONTDIR") AndAlso headerText.Contains("FONTRES") Then Return FontType.Raster End If End Using Catch ex As Exception Throw End Try Return FontType.Unknown End Function ''' <summary> ''' Specifies the type of a font file. ''' </summary> Public Enum FontType As Short ''' <summary> ''' A TrueType font (.ttf). ''' <para></para> ''' This is the traditional TrueType format developed by Apple™. ''' </summary> TrueType ''' <summary> ''' An OpenType font with PostScript (CFF) outlines (.otf). ''' <para></para> ''' These fonts use the .otf container from the OpenType format jointly developed by Adobe™ and Microsoft™. ''' </summary> OpenTypeCFF ''' <summary> ''' An OpenType font with TrueType outlines (.ttf). ''' <para></para> ''' Technically OpenType, but uses TrueType outlines inside a .ttf container. ''' <para></para> ''' Sometimes called 'OpenType-TT' for distinction. ''' </summary> OpenTypeTT ''' <summary> ''' A Raster / Bitmap font (.fon) with fixed-size glyphs. ''' <para></para> ''' Raster fonts store each character as a pixel grid, not as scalable outlines. ''' <para></para> ''' These were commonly used in older versions of Windows and DOS, and are mostly legacy fonts today. ''' </summary> Raster ''' <summary> ''' Font file type is not recognized. ''' <para></para> ''' It might be an unsupported format, corrupted file or not a valid font file. ''' </summary> Unknown ''' <summary> ''' File does not seems a valid font file (file size is too small). ''' </summary> Invalid End Enum ''' <summary> ''' Determines whether a font file is already installed in the current computer. ''' </summary> ''' ''' <param name="fontFilePathOrName"> ''' Either the full path to the font file or just the file name ''' (e.g., <b>"C:\font.ttf"</b> or else <b>"font.ttf"</b>). ''' </param> ''' ''' <param name="systemWide"> ''' If <see langword="True"/>, performs a system-wide search for the font installation (under <c>HKEY_LOCAL_MACHINE</c> base key). ''' otherwise, searches only the current user's installed fonts (under <c>HKEY_CURRENT_USER</c> base key). ''' </param> ''' ''' <returns> ''' If the font file is not installed, returns <see cref="CheckFontInstallationResults.NotInstalled"/>; ''' otherwise, can return a combination of <see cref="CheckFontInstallationResults"/> values. ''' </returns> <DebuggerStepThrough> Public Shared Function CheckFontInstallation(fontFilePathOrName As String, systemWide As Boolean) As CheckFontInstallationResults Dim fontFilePath As String = UtilFonts.BuildFullFontFilePath(fontFilePathOrName, systemWide) Dim fontFileName As String = Path.GetFileName(fontFilePath) Dim fontTitle As String = UtilFonts.GetFontFriendlyName(fontFilePath, includeSuffix:=False) Dim fontTitleTT As String = $"{fontTitle} (TrueType)" Dim fontTitleOT As String = $"{fontTitle} (OpenType)" Dim result As CheckFontInstallationResults = CheckFontInstallationResults.NotInstalled Dim baseKey As RegistryKey = If(systemWide, Registry.LocalMachine, Registry.CurrentUser) Dim regKeyPath As String = "SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts" Try Using key As RegistryKey = baseKey.OpenSubKey(regKeyPath, writable:=False) ' Fonts registry key does not exists. If key Is Nothing Then Exit Try End If Dim valueFontTitle As Object = CStr(key.GetValue(fontTitle)) Dim valueFontTitleTT As Object = CStr(key.GetValue(fontTitleTT)) Dim valueFontTitleOT As Object = CStr(key.GetValue(fontTitleOT)) Dim fontTitles() As String = {fontTitle, fontTitleTT, fontTitleOT} For Each title As String In fontTitles Dim regValue As Object = key.GetValue(title, Nothing, RegistryValueOptions.DoNotExpandEnvironmentNames) ' Font title found in registry If regValue IsNot Nothing Then result = result Or CheckFontInstallationResults.FontTitleFound ' Font file matches? If String.Equals(CStr(regValue), fontFileName, StringComparison.OrdinalIgnoreCase) Then result = result Or CheckFontInstallationResults.FileNameFound End If End If If result = (CheckFontInstallationResults.FontTitleFound Or CheckFontInstallationResults.FileNameFound) Then Exit For End If Next If Not result.HasFlag(CheckFontInstallationResults.FileNameFound) Then ' Additional check required for consistency because the font file name ' could be specified in a value name that differs from the compared font title vale names. Dim valueNames As String() = Array.ConvertAll(key.GetValueNames(), Function(str As String) str.ToLowerInvariant()) If valueNames.Contains(fontFileName.ToLowerInvariant()) Then result = result Or CheckFontInstallationResults.FileNameFound End If End If End Using Catch ex As Exception Throw End Try Return result End Function ''' <summary> ''' Specifies the installation status of a font file on the current computer. ''' </summary> <Flags> Public Enum CheckFontInstallationResults As Short ''' <summary> ''' The font is not installed. ''' </summary> NotInstalled = 0S ''' <summary> ''' A registry value with the font file name is present in the Windows <b>Fonts</b> registry key. ''' </summary> FileNameFound = 1S << 0S ''' <summary> ''' A registry value name with the font title ''' (which also may have suffix: "<b>(TrueType)</b>" or "<b>(OpenType)</b>") ''' is present in the Windows <b>Fonts</b> registry key. ''' </summary> FontTitleFound = 1S << 1S End Enum ''' <summary> ''' Installs a font file permanently on the current computer. ''' </summary> ''' ''' <param name="fontFile"> ''' The path to the font file to install (e.g., <b>"C:\font.ttf"</b>). ''' </param> ''' ''' <param name="systemWide"> ''' If <see langword="True"/>, performs a system-wide installation; ''' otherwise, installs the font for the current user only. ''' </param> ''' ''' <param name="useTrueTypeNameSuffix"> ''' If <see langword="True"/>, appends the "<b>(TrueType)</b>" suffix when ''' naming the font registry value for TrueType and OpenType fonts. ''' This is what Microsoft Windows does by default. ''' <para></para> ''' If <see langword="False"/>, appends the appropriate suffix for the font type: "<b>(TrueType)</b>" or "<b>(OpenType)</b>". ''' <para></para> ''' This setting does not apply to .fon files. ''' </param> ''' ''' <param name="addFontToSystemTable"> ''' If <see langword="True"/>, the font resource is loaded into memory and immediately available to other applications. ''' </param> <DebuggerStepThrough> Public Shared Sub InstallFont(fontFile As String, systemWide As Boolean, useTrueTypeNameSuffix As Boolean, addFontToSystemTable As Boolean) Dim isFontInstalled As Boolean Try isFontInstalled = (UtilFonts.CheckFontInstallation(fontFile, systemWide) <> UtilFonts.CheckFontInstallationResults.NotInstalled) Catch ex As FileNotFoundException ' Use this exception message for readness, since CheckFontInstallation calls BuildFullFontFilePath, which modifies the path. Dim msg As String = $"The font file does not exist: '{fontFile}'" Throw New FileNotFoundException(msg, fontFile) Catch ex As Exception Throw End Try If isFontInstalled Then Dim msg As String = $"The font file is already installed: '{fontFile}'" Throw New InvalidOperationException(msg) End If Dim fontFileName As String = Path.GetFileName(fontFile) Dim fontTitle As String = UtilFonts.GetFontFriendlyName(fontFile, includeSuffix:=True) If useTrueTypeNameSuffix Then fontTitle = fontTitle.Replace(" (OpenType)", " (TrueType)") End If Dim fontsDir As String = If(systemWide, Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Fonts"), Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Microsoft\Windows\Fonts")) If Not Directory.Exists(fontsDir) Then Directory.CreateDirectory(fontsDir) End If Dim fontFileDestPath As String = Path.Combine(fontsDir, fontFileName) If File. Exists(fontFileDestPath ) Then Dim msg As String = $"Font file already exists in Fonts directory: {fontFileDestPath}" Throw New InvalidOperationException(msg) End If Try File. Copy(fontFile, fontFileDestPath, overwrite: =False) Catch ex As Exception Dim msg As String = $"Error copying font file to Fonts directory: '{fontFileDestPath}'" Throw New IOException(msg, ex) End Try Dim baseKey As RegistryKey = If(systemWide, Registry.LocalMachine, Registry.CurrentUser) Dim regKeyPath As String = "SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts" Dim registrySuccess As Boolean Try Using key As RegistryKey = baseKey.CreateSubKey(regKeyPath, writable:=True) key.SetValue(fontTitle, fontFileName, RegistryValueKind.String) End Using registrySuccess = True Catch ex As Exception Throw Finally If Not registrySuccess Then ' Attempt to delete the copied font file in Fonts directory ' when registry manipulation has failed. Try File. Delete(fontFileDestPath ) Catch ' Ignore deletion exceptions; cleanup best effort. End Try End If End Try ' Add the font to the system font table. If addFontToSystemTable Then Dim fontsAdded As Integer = DevCase.Win32.NativeMethods.AddFontResource(fontFileDestPath) Dim win32Err As Integer = Marshal.GetLastWin32Error() If fontsAdded = 0 OrElse win32Err <> 0 Then Dim msg As String = $"Failed to add font to the system font table '{fontFileDestPath}'" Throw New InvalidOperationException(msg, New Win32Exception(win32Err)) End If ' Notify all top-level windows so they can immediately list the added font. DevCase.Win32.NativeMethods.SendMessage(DevCase.Win32.Common.Constants.HWND_BROADCAST, WindowMessages.WM_FontChange, IntPtr.Zero, IntPtr.Zero) End If End Sub ''' <summary> ''' Uninstalls a font file from the current computer. ''' </summary> ''' ''' <param name="fontFilePathOrName"> ''' Either the full path to the font file or just the file name ''' (e.g., <b>"C:\font.ttf"</b> or else <b>"font.ttf"</b>). ''' </param> ''' ''' <param name="systemWide"> ''' If <see langword="True"/>, performs a system-wide uninstallation; ''' otherwise, uninstalls the font for the current user only. ''' </param> ''' ''' <param name="deleteFile"> ''' If <see langword="True"/>, permanently deletes the font file from disk. ''' <para></para> ''' Note: The font file deletion will be performed after deleting associated registry values with the font file. ''' </param> <DebuggerStepThrough> Public Shared Sub UninstallFont(fontFilePathOrName As String, systemWide As Boolean, deleteFile As Boolean) Dim fontFilePath As String = UtilFonts.BuildFullFontFilePath(fontFilePathOrName, systemWide) Dim fontFileName As String = Path.GetFileName(fontFilePath) Dim checkFontInstallation As CheckFontInstallationResults = UtilFonts.CheckFontInstallation(fontFilePath, systemWide) Dim isFontInstalled As Boolean = (checkFontInstallation <> UtilFonts.CheckFontInstallationResults.NotInstalled) If Not isFontInstalled Then Dim msg As String = $"The font file is not installed: '{fontFilePath}'" Throw New InvalidOperationException(msg) End If Dim fontTitle As String = UtilFonts.GetFontFriendlyName(fontFilePath, includeSuffix:=False) Dim fontTitleTT As String = $"{fontTitle} (TrueType)" Dim fontTitleOT As String = $"{fontTitle} (OpenType)" Dim baseKey As RegistryKey = If(systemWide, Registry.LocalMachine, Registry.CurrentUser) Dim regKeyPath As String = "SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts" Try Using key As RegistryKey = baseKey.OpenSubKey(regKeyPath, writable:=True) Dim valueNames As String() = key.GetValueNames() ' Compare font title. If checkFontInstallation.HasFlag(CheckFontInstallationResults.FontTitleFound) Then If valueNames.Contains(fontTitle) Then key.DeleteValue(fontTitle, throwOnMissingValue:=True) ElseIf valueNames.Contains(fontTitleTT) Then key.DeleteValue(fontTitleTT, throwOnMissingValue:=True) ElseIf valueNames.Contains(fontTitleOT) Then key.DeleteValue(fontTitleOT, throwOnMissingValue:=True) End If ElseIf checkFontInstallation.HasFlag(CheckFontInstallationResults.FileNameFound) Then For Each valueName As String In valueNames ' Compare font file name. Dim value As String = CStr(key.GetValue(valueName)) If String.Equals(value, fontFileName, StringComparison.OrdinalIgnoreCase) Then key.DeleteValue(valueName, throwOnMissingValue:=True) Exit For End If Next End If End Using Catch ex As Exception Throw End Try If deleteFile Then Dim fontsDir As String = If(systemWide, Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Fonts"), Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Microsoft\Windows\Fonts")) Dim fontFileDestPath As String = Path.Combine(fontsDir, fontFileName) ' First attempt to delete the file. Try File. Delete(fontFileDestPath ) Catch End Try If File. Exists(fontFileDestPath ) Then ' Remove the font from the system font table, ' because in case of 'AddFontResource' was called for this font file in the current user session, ' the font will remain loaded in memory and cannot be deleted until unloaded from memory. Dim result As Boolean = DevCase.Win32.NativeMethods.RemoveFontResource(fontFileDestPath) Dim win32Err As Integer = Marshal.GetLastWin32Error() If result Then ' Notify all top-level windows so they can immediately delist the removed font. DevCase.Win32.NativeMethods.SendMessage(DevCase.Win32.Common.Constants.HWND_BROADCAST, WindowMessages.WM_FontChange, IntPtr.Zero, IntPtr.Zero) Else ' Ignore throwing an exception, since we don't really know if the font file was loaded in memory. 'Dim msg As String = $"Failed to remove font file from the system font table: '{fontFileDestPath}'" 'Throw New InvalidOperationException(msg, New Win32Exception(win32Err)) End If ' Second attempt to delete the file. Try File. Delete(fontFileDestPath ) Catch End Try End If If File. Exists(fontFileDestPath ) Then ' Ensure that the 'FontCache' service is stopped, as it could habe blocked the font file. Using sc As New ServiceController("FontCache") Dim previousStatus As ServiceControllerStatus = sc.Status If (sc.Status <> ServiceControllerStatus.Stopped) AndAlso (sc.Status <> ServiceControllerStatus.StopPending) Then Try sc.Stop() sc.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(3)) Catch ex As Exception ' Ignore throwing an exception, ' since we don't really know if the 'FontCache' service have blocked the font file at all. 'If sc.Status <> ServiceControllerStatus.Stopped Then ' Dim msg As String = "Unable to stop 'FontCache' service." ' Throw New InvalidOperationException(msg, ex) 'End If End Try End If ' Third and last attempt to delete the file. Try File. Delete(fontFileDestPath ) Catch ex As Exception Dim msg As String = $"Error deleting font file from Fonts directory: '{fontFileDestPath}'" Throw New IOException(msg, ex) Finally ' Restore previous 'FontCache' service status if it was started and not in automatic mode. If sc.StartType <> ServiceStartMode.Automatic AndAlso ( (previousStatus = ServiceControllerStatus.Running) OrElse (previousStatus = ServiceControllerStatus.StartPending) ) AndAlso sc.Status <> ServiceControllerStatus.Running Then Try sc.Start() sc.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(0.25)) Catch ' Ignore throwing an exception; best effort. End Try End If End Try End Using End If End If End Sub ''' <summary> ''' Builds a full path to a font file from the given value in <paramref name="fontFilePathOrName"/> parameter. ''' <para></para> ''' If the provided file path exists, it is returned as-is; otherwise, ''' the function constructs and returns a full file path based on ''' the value of <paramref name="systemWide"/> parameter. ''' <para></para> ''' Note: This function does not check whether the resulting file path exists. ''' </summary> ''' ''' <param name="fontFilePathOrName"> ''' Either the full path to the font file or just the file name ''' (e.g., <b>"C:\font.ttf"</b> or else <b>"font.ttf"</b>). ''' <para></para> ''' If the provided path exists, the function returns this path as-is. ''' </param> ''' ''' <param name="systemWide"> ''' If <see langword="True"/>, the function constructs a full font file path from the system's Fonts directory ''' (<b>%WINDIR%\Fonts</b>); otherwise, it constructs a full font file path from the current user's local Fonts directory ''' (<b>%LOCALAPPDATA%\Microsoft\Windows\Fonts</b>). ''' <para></para> ''' Note: The <paramref name="systemWide"/> parameter is ignored if ''' <paramref name="fontFilePathOrName"/> already specifies an existing file path. ''' </param> ''' ''' <returns> ''' The resulting full path to the font file. ''' </returns> <DebuggerStepThrough> Private Shared Function BuildFullFontFilePath(fontFilePathOrName As String, systemWide As Boolean) As String If File. Exists(fontFilePathOrName ) Then Return fontFilePathOrName End If Dim fontFileName As String = Path.GetFileName(fontFilePathOrName) If String.IsNullOrWhiteSpace(fontFileName) Then Throw New ArgumentException("The font file path or name is malformed or empty.", NameOf(fontFilePathOrName)) End If Dim fontsDir As String = If(systemWide, Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Fonts"), Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Microsoft\Windows\Fonts")) Return Path.Combine(fontsDir, fontFileName) End Function 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
|
|
|
|
|
|
|