Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Change one font style without changing others

Status
Not open for further replies.

Stopher

Programmer
Jan 12, 2002
29
US
I have a rich text box in which I would like to have multiple font styles be used in different parts of the text.

If I select a piece of text and click on my designated 'bold' button, it turns bold. However, if half the selected text is italic and the other half is regular, it either becomes all bold italic or all just bold.

I've searched the font object up and down, but it seems the only way to set a single font style at runtime is to completely rebuild the font object. Any ideas on how I can get around this and just set ONE font style without affecting the others?

Thanks, Stopher
 
The RichTextBox control has a property called SelectionFont,

If you select the text you want changing, retrieve the current font (You could use this to change the state of B/I/U buttons), then apply the new font using:

RTB.SelectionFont = New Font(RTB.SelectionFont, NewStyle)

Hope this helps
 
Thanks cjelec for replying.

Unfortunately, this doesn't solve the problem, as when you create the new font, it doesn't carry over the current font characteristics. The font given in SelectionFont is only the font for the BEGINNING of the selection, as the selection could have more than one font face, size and/or characteristics and it can't return two separate fonts.

The only way I could figure out how to do this was by modifying the RTF codes directly, which I have to say is a real pain compared to how simple it used to be :(

Thanks for the help anyhow,
Stopher
 
You could For loop through the selected text and make your change to each character, I think this is how Word does it because if you have a 100+ page document and select all then change the font name for example, it seems to hang suggesting that it is looping through all the characters selected.

A bit of code for you to try:
Code:
Dim SelectStart as Integer = RTB.SelectionStart
Dim SelectLength as Integer = RTB.SelectionLength
Dim NewStyle as FontStyle

For Index as Integer = SelectStart To SelectStart + SelectLength

   RTB.Select(Index, 1)

   NewStyle = RTB.SelectionFont.Style + StyleToApply '- if removing
   RTB.SelectionFont = New Font(RTB.SelectionFont, NewStyle)

Next

RTB.Select(SelectStart, SelectLength)

I havn't tested above code, but i hope it gives you an idea.
You may need to change the For line to read '... To (SelectStart + SelectLength) - 1' if you get index out of range errors... or an extra character is being converted...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top