In C#, how can I send/write a string to a RichTextBox control on my internal WinForm, where I can change the font style of a few words of the string to either Bold or Italic style and then go back to normal style?
Sample code: rtb.Text = "Hello *this* is my world.";
I haven't tried anything myself as I don't know how this can be done. As to what I'm looking to be able to do is send/write a string starting in a normal style and then being able to switch between two or more different styles as needed. For example, changing to bold style then go back to normal style one or more time within the same string.
Any time you set the .Text
property of your RTB, you are going to lose all the formatting in it.
Instead, you would change the Font assigned to the current Selection. You could let the user make a selection, or you could search for a String. In the example below, I'm searching for "this" and changing it to Bold (button1) or Regular (button2):
private void Form1_Load(object sender, EventArgs e)
{
rtb.Text = "Hello this is my world.";
}
private void button1_Click(object sender, EventArgs e)
{
String find = "this";
int position = rtb.Find(find);
if (position != -1)
{
rtb.SelectionFont = new Font(rtb.SelectionFont, FontStyle.Bold);
}
}
private void button2_Click(object sender, EventArgs e)
{
String find = "this";
int position = rtb.Find(find);
if (position != -1)
{
rtb.SelectionFont = new Font(rtb.SelectionFont, FontStyle.Regular);
}
}