VB.NET Break State when Changing Font

blinkor12 101 Reputation points
2021-10-24T03:28:52.437+00:00

I created a custom control that has a label in it with VB.NET.

I dragged this control onto my designer and want to update its font (with a font file stored in the application) when the form loads. This works fine for a bit, but whenever I interact with the control (such as changing the text or clicking it), it throws a Parameter Not Valid exception and forces the application to enter a break state.

My code changes the font of a specific control on the form when it loads. It is shown below. Note that the font file is saved in \assets\fonts\roboto.ttf and this code is executed when the form loads (it doesn't work if I embed it in the custom control itself)

'Note that System.Drawing.Text is imported.

Private Sub mainForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    Dim pfc As New PrivateFontCollection()
    Dim fontCollectionBaseDIR As String = Application.StartupPath & "\assets\fonts\"
    pfc.AddFontFile(fontCollectionBaseDIR & "roboto.ttf")
    Me.TheCustomControl.Label1.Font = New Font(pfc.Families(0), 10.8, FontStyle.Bold)

End Sub

I have to set these fonts when the application is running from a local file because I cannot be sure that the font is installed on the user's system.

ERROR CONTENT:

System.ArgumentException
  HResult=0x80070057
  Message=Parameter is not valid.
  Source=System.Drawing
  StackTrace:
   at System.Drawing.FontFamily.GetName(Int32 language)
   at System.Drawing.FontFamily.get_Name()
   at System.Windows.Forms.Internal.WindowsFont.FromFont(Font font, WindowsFontQuality fontQuality)
   at System.Windows.Forms.Internal.WindowsGraphicsCacheManager.GetWindowsFont(Font font, WindowsFontQuality fontQuality)
   at System.Windows.Forms.TextRenderer.DrawText(IDeviceContext dc, String text, Font font, Rectangle bounds, Color foreColor, TextFormatFlags flags)
   at System.Windows.Forms.Label.OnPaint(PaintEventArgs e)
   at System.Windows.Forms.Control.PaintWithErrorHandling(PaintEventArgs e, Int16 layer)
   at System.Windows.Forms.Control.WmPaint(Message& m)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.Label.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

This error usually occurs when I try to modify the control's element (such as changing something else) or clicking it. When the form first loads, the custom control's font changes correctly. However, when the control is interacted with, it forces the application into a break state.

VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,580 questions
{count} votes