首页 > 解决方案 > 如何在单击按钮时删除 RichTextBox 中的单词?

问题描述

我正在用 C# 制作一个小应用程序,我有一个文本框、3 个按钮,每个按钮都是一个特定的坏词。如果我点击它,它会在文本中找到这个词并将其删除。

按钮 1 命名为 btn1,按钮 2 命名为 btn2,按钮 3 命名为 btn3。我正在考虑使用 RichTextBoxFinds,但我一开始就被卡住了。

    private void btn1(object sender, EventArgs e)
    {
        Button btn1 = sender as Button;
        string word1 = btn1.Text;
      if (RichTextBox.Find(word1) = true)
        {
            RichTextBox.Delete(word1);
        }
    }

标签: c#winforms

解决方案


我不确定从文本中删除坏词是否明智,而不让用户有机会决定替代描述。只是删除单词可能会使其不可读,甚至会给出相反的含义。但是,嘿,这是你的要求。

让我们首先创建一个可重用的方法来从任何 RichTextBox 中删除单词,而不仅仅是您的 RichTextBox。我将把它作为一个扩展方法来做,这样你就可以将它用于你的应用程序中的每个 RicthTextBox。请参阅揭秘的扩展方法

public static void RemoveWord(this RichTextBox richTextBox, string wordToRemove)
{
    // We only want to find whole words. Don't want any flickering highlights
    RichTextBoxFinds finds = RichTextboxFinds.WholeWord | RichTextBoxFinds.NoHighLight;
    int wordIndex = richTextBox.Find(wordToRemove, finds);
    while (wordIndex >= 0)
    {
        // occurence found.
        // in RichTextBox a word is removed by selecting it, and replace it
        richTextBox.Select(wordIndex, wordToRemove.Length);
        richTextBox.SelectedText = String.Empty;

        // find the next bad word:
        wordIndex = richTextBox.Find(wordToRemove, finds);
    } 
}

用法:

RichTextBox myRichTextBox = ...
string wordToRemove = ...

myRichTextbox.RemoveWord(wordToRemove);

有点整洁,不是吗?看起来好像 RemoveWord 是 RichTextbox 的标准方法。

回到你的问题

所以你有几个按钮,每个按钮都有一个功能,它应该从 RichTextBox 中删除某个单词的所有出现。这看起来像一种特殊的按钮。考虑为它创建一个特殊的类。

class RemoveBadWordButton : Button
{
    public string BadWord {get; set;}
    public RichTextBox RichTextBox {get; set;}

    protected override OnButtonClicked()
    {
         this.RichTextBox.RemoveWord(this.BadWord);
    }
}

如果更改很小,人们往往不会为它创建特殊的类,而是让拥有按钮的 Form 执行特殊功能。如果您为此选择,请考虑使用Button.Tag分配必须删除的单词。

button1.Tag = "badword1";
button2.Tag = "badword2";
this.button1.Click += this.OnBadWordButtonClicked);
this.button2.Click += this.OnBadWordButtonClicked);

private void OnBadWordButtonClicked(object sender, EventArgs e)
{
    Button badWordButton = (Button)sender;
    string badWord = badWordButton.Tag.ToString();
    this.RichTextBox1.RemoveWord(badWord);
}

优势:只有一种方法适用于所有 BadWord 按钮。如果您决定添加另一个坏词删除按钮,则代码更改很少。


推荐阅读