Code to apply minimum Font size to a field when resizing

Simon 466 Reputation points
2023-07-17T17:08:13.5666667+00:00

How do I apply a specific Font size to a field, when resizing a Form, so that the font size does not become smaller than Font Size pt. 8.

Thank you

Developer technologies Visual Studio Debugging
Developer technologies VB
Developer technologies Visual Studio Other
{count} votes

Accepted answer
  1. Jiachen Li-MSFT 34,221 Reputation points Microsoft External Staff
    2023-07-18T06:25:21.5433333+00:00

    Hi @Simon

    Please check if the following code helps.

    Calculate the scaled font size in CalculateDesiredFontSize, and then use judgments in ApplyFontSize to limit the minimum font.

    Private Sub Form1_Resize(sender As Object, e As EventArgs) Handles Me.Resize
        ApplyFontSize(TextBox1)
        ApplyFontSize(Label1)
        ' Add more controls that need to have font size limited to 8 points
    End Sub
    
    Private Sub ApplyFontSize(control As Control)
        Dim desiredFontSize As Single = CalculateDesiredFontSize()
        If desiredFontSize < 8 Then
            desiredFontSize = 8
        End If
        control.Font = New Font(control.Font.FontFamily, desiredFontSize, control.Font.Style)
    End Sub
    
    Private Function CalculateDesiredFontSize() As Single
        ' Adjust the calculation based on your desired logic
        Dim desiredFontSize As Single = Me.ClientSize.Width * 0.02
        Return desiredFontSize
    End Function
    
    

    Best Regards.

    Jiachen Li


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.