在文本框或richtextbox中,如何在单击时删除封闭的文本括号

时间:2016-03-15 23:25:10

标签: c# winforms textbox richtextbox

考虑ritchTextbox中的给定文本是

Have [a wonderful] [day]!

当我点击"一个精彩的"时,如何删除封闭的支架?

结果:

Have a wonderful [day]!    

1 个答案:

答案 0 :(得分:2)

对于TextBox或RichTextBox,将以下内容添加到Click事件:

        int SelectionStart = this.richTextBox1.SelectionStart - 1;
        if (SelectionStart > 0)
        {
            string Text = this.richTextBox1.Text;
            int Start = Text.LastIndexOf('[', SelectionStart);
            int End = Text.IndexOf(']', SelectionStart);
            int OtherStart = Text.LastIndexOf(']', SelectionStart);
            int OtherEnd = Text.IndexOf('[', SelectionStart);
            if (Start > -1 && End > -1 && (OtherStart < 0 || OtherStart < Start) && (OtherEnd < 0 || OtherEnd > End))
            {
                this.richTextBox1.Text = Text.Remove(Start, 1).Remove(End - 1, 1);
            }
        }