且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C# 将 RichTextBox 中字符串的一部分加粗

更新时间:2023-11-06 22:27:34

此问题已在评论中@dash 链接的帮助下解决.链接:http://msmvps.com/blogs/deborahk/archive/2009/10/31/richtextbox-styles.aspx

This issue was solved with help from @dash's link in the comments. Link: http://msmvps.com/blogs/deborahk/archive/2009/10/31/richtextbox-styles.aspx

这是我的代码,因为它现在代表同一个按钮(虽然我已经重命名了它).这可能不是解决这个问题的最干净的解决方案,但我达到了预期的结果,所以我很满意.评论中对此进行了解释.

This is my code as It stands now for the same button (although I have renamed it since). This may not be the cleanest solution to this issue but I achieved the desired result so I'm happy with it. It is explained in the comments.

        private void send_Click(object sender, EventArgs e)
    {
        if (entryBox.Text != "")
        {
            listData.Add(entryBox.Text);
            // Remove the linebreak caused by pressing return
            SendKeys.Send("\b");

            // Empty the array string
            ArrayData = "";

            foreach (string textItem in listData)
            {
                ArrayData = ArrayData + "You >> " + textItem + "\r\n";
            }
            entryBox.Focus();
            displayBox.Text = "";
            displayBox.Refresh();
            displayBox.Text = ArrayData;

            // Format the "You >>"
            displayBox.SelectionStart = 0;
            displayBox.SelectionLength = 6;
            displayBox.SelectionFont = new Font(displayBox.Font, FontStyle.Bold);
            displayBox.SelectionColor = Color.Crimson;
            displayBox.SelectionLength = 0;
            string wordToFind = "You >>";
            int startIndex = 0;
            while (startIndex > -1)
            {
                startIndex = displayBox.Find(wordToFind, startIndex + 1,
                                displayBox.Text.Length,
                                RichTextBoxFinds.WholeWord);
                if (startIndex > -1)
                {
                    displayBox.Select(startIndex, wordToFind.Length);
                    displayBox.SelectionFont = new Font(displayBox.Font, FontStyle.Bold);
                    displayBox.SelectionColor = Color.Crimson;
                }
            }
            // Reset the entry box to empty
            entryBox.Text = "";

        }
        // Remove the linebreak caused by pressing return
        SendKeys.Send("\b");
    }

我希望这能为遇到类似问题的人提供一些帮助!

I hope this provides anyone with a similar problem some help!

:丹