• 0

[VB.NET] Applying more than 1 font style


Question

Hi. I am working on a very simple text editor. I wonder how to apply more than 1 font style (eg. Bold + Underline, Bold + Italic, Italic + Underline) on selected text in a RichTextBox object?

I created a button to bold the selected text, and the codes:

Private Sub BoldTextButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BoldTextButton.Click
		'Create new Font object and set its properties
		Dim ReplaceFont As New Font(Me.DocContentRichTextBox.SelectionFont, FontStyle.Bold)
		'Apply ReplaceFont onto selected text
		Me.DocContentRichTextBox.SelectionFont = ReplaceFont
	End Sub

This piece of code does work, but it will cancel the current font style, and make the selected text become bold ONLY; if the original text has italic font style, after pressing the button, the text will have bold font style only.

So, how do I apply "append" font style in VB.NET? Thanks very much.

Edit: I have found a solution on the Internet... I just have to modify my codes a little bit:

Private Sub BoldTextButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BoldTextButton.Click
		'Get font of selected text
		Dim selectedTextFont As Font = Me.DocContentRichTextBox.SelectionFont
		'Create new Font object and set its properties
		Dim ReplaceFont As New Font(selectedTextFont, selectedTextFont.Style Xor FontStyle.Bold)
		'Apply ReplaceFont onto selected text
		Me.DocContentRichTextBox.SelectionFont = ReplaceFont
	End Sub

Here is my new question: Why do I have to use XOR, rather than AND, between the FontStyle? I thought using AND is to "adding up" the FontStyle.

Edited by Gundamdriver

1 answer to this question

Recommended Posts

  • 0

I would have thought it was OR that you would have had to use, but no matter, I'm not a VB programmer.

The reason is that the FontStyle enum is also defined as having the Flags attribute which means its values can be combined to create new ones eg: FontStyle.Bold OR FontStyle.Italic

This will apply the Bold and Italic style to the selected text.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.