简体   繁体   English

如何在richTextBox上使字符串粗体的特定部分?

[英]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 ! 我有一个基于Form和2 richTextBoxes的聊天应用程序!

richTextBox1 is used to display all conversation richTextBox1用于显示所有对话
richTextBox_TextToSend is used to type in the message to send richTextBox_TextToSend用于键入要发送的消息

when a user types a message and hit the enter button, the entered text will appear in richTextBox1 当用户键入消息并按Enter键时,输入的文本将出现在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) 字符串类型的变量from包含发送消息的人的名称(使用该应用程序的用户)

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.... Chakib Yousfi :你好...

instead of 代替

Chakib Yousfi : Hello... Chakib Yousfi:你好...

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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