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

与世无争的帅哥 提交于 2019-12-02 16:06:21

问题


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 .


回答1:


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);



回答2:


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);

    }
}


来源:https://stackoverflow.com/questions/14921835/how-to-make-a-specific-part-of-string-bold-on-richtextbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!