简体   繁体   中英

How to make a specific part of string Bold on richTextBox?

I have a chat application that is based on a Form and 2 richTextBoxes !

richTextBox1 is used to display all conversation
richTextBox_TextToSend is used to type in the message to send

when a user types a message and hit the enter button, the entered text will appear in richTextBox1

private void button1_Click(object sender, EventArgs e)
    {
        // insert message to database
        if(richTextBox_TextToSend.TextLength>0) {

        string txt = richTextBox_TextToSend.Text;

        // send the typed message
        sendMessage(from,to,task_id,txt);

        // show the typed text in the richTextBox1
        richTextBox1.Text += from+": "+richTextBox_TextToSend.Text+"\n";
        richTextBox_TextToSend.Clear();



        }
    }

The variable from of type string holds the name of who send the message (the user using the application)

How to display the name only in bold and other text in normal font style so after typing the message, I see

Chakib Yousfi : Hello....

instead of

Chakib Yousfi : Hello...

Any help would be highly appreciated .

在此处输入图片说明

Use this code :

private void button1_Click(object sender, EventArgs e)
{
    // insert message to database
    if(richTextBox_TextToSend.TextLength>0) {

    string txt = richTextBox_TextToSend.Text;
    int start = richTextBox1.TextLength;
    string newMessage = from + ": " + richTextBox_TextToSend.Text + Environment.NewLine;

    // send the typed message
    sendMessage(from,to,task_id,txt);

    // show the typed text in the richTextBox1
    richTextBox1.AppendText(newMessage);
    richTextBox_TextToSend.Clear();

    richTextBox1.Select(start, from.Length);
    richTextBox1.SelectionFont = New Font(richTextBox1.Font, FontStyle.Bold);

    }
}

First, you should select the text you want to make bold:

richTextBox1.SelectionStart = 0;
richTextBox1.SelectionLength = 13;

And then you can define the style for the selected text:

richTextBox1.SelectionFont = new Font(richTextBox1.Font, FontStyle.Bold);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM