【问题标题】:How to make a specific part of string Bold on richTextBox?如何在richTextBox上制作字符串的特定部分Bold?
【发布时间】:2013-02-17 23:15:56
【问题描述】:

我有一个基于表单和 2 个richTextBoxes 的聊天应用程序!

richTextBox1 用于显示所有对话
richTextBox_TextToSend 用于输入要发送的消息

当用户输入消息并按下回车键时,输入的文本将出现在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();



        }
    }

字符串类型的变量from保存发送消息的人(使用应用程序的用户)的名称

如何仅以粗体显示名称并以正常字体样式显示其他文本,因此在键入消息后,我看到

Chakib Yousfi :你好....

而不是

Chakib Yousfi : 你好...

任何帮助将不胜感激。

【问题讨论】:

  • 只需将用户名设置为 bold,但我在这里看不到任何用户名文本..
  • @SonerGönül 显然 Chakib Yousfi 是用户名。

标签: c# .net richtextbox


【解决方案1】:

使用此代码:

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

    }
}

【讨论】:

    【解决方案2】:

    首先,您应该选择要加粗的文本:

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

    然后您可以为所选文本定义样式:

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

    【讨论】:

      猜你喜欢
      • 2021-09-25
      • 2018-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-17
      • 2022-01-24
      相关资源
      最近更新 更多