Terabithia Terabithia - 5 months ago 33
Vb.net Question

User Change Font of Selected Text in RichTextBox

This should be easy, however it is eluding me. I have a RichTextBox in VB.NET that the user enters text in. I want them to be able to select some text, then change the font properties of the selection.

Answer

Here is something I have quickly written up for you.

It will get ALL of the installed fonts on the system and add them to a combobox, so you wont have to add them all manually.

Also I have made it so whenever you change the font type for a combobox that I have added, It will update the RichTextBox's font.

Imports System.Drawing.Text
Public Class Form1
''CREATE ANOTHER COMBOBOX TO CHANGE THE SIZE OF THE TEXT USING THE SAME METHOD
''AS THE FONT COMBOBOX.
Dim FONTSIZE = 8
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim InstalledFonts = New InstalledFontCollection
    Dim FontFamilies() As FontFamily = InstalledFonts.Families

    For Each Font As FontFamily In FontFamilies
        ComboBox1.Items.Add(Font.Name)
    Next
    ''THE END USER WONT BE ABOUT TO EDIT THE INSTALLED ITEMS IN THE COMBOBOX
    ''THE STARTING FONT IS CONSOLAS
    ComboBox1.DropDownStyle = ComboBoxStyle.DropDownList
    ComboBox1.Text = "Consolas"
    End Sub

Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
    ''THIS WILL CHANGE THE HIGHLIGHTED "SELECTED" TEXT FONT ONLY
    ''AS ASKED FOR IN QUESTION
    RichTextBox1.SelectionFont = New Drawing.Font(ComboBox1.Text, FONTSIZE)
End Sub
End Class

You will need to add a combobox to your form and a richtextbox for this too work.

If you have any trouble, let me know and I'll try and help you work.

Comments