2016-11-10 53 views
-1

我正在为自己制作基本代码编辑器的应用程序。 当创建自动括号时,我遇到了一个问题。 当我的光标是在文本框中的第4行和我按下“(”它移动“(”到线文本框1和在其线增加了一个“)” 4.无法在文本框中自动关闭括号

这是我的代码:

private void editorTB_KeyPress(object sender, KeyPressEventArgs e) 
    { 
     bool CSharpMode = true; 

     if (CSharpMode == true) 
     { 
      if (e.KeyChar == '(') 
      { 
       editorTB.Text += ")"; 
      } 
     } 
    } 

editorTB是我richtextbox1控制。

我希望有人能帮助我解决这个问题。在此先感谢!

+1

你需要显示更多的代码,你在哪里设置editorTB的值? – Jawad

+0

我刚刚创建了一个文本框控件并将其命名为editorTB。 – Thow

+0

将editorTB.Text更改为textbox1.Text,以便更容易理解 – Thow

回答

1

这段代码插入后")"炭炭"("中的任何位置文本框。

情况:TEXT(

输出:文本()

情况1:TE(XT

输出1:TE()XT

检查此keypress事件。关键是这里e.Handled是真的。否则它不会工作。

 if (e.KeyChar == '(') 
     { 
      e.Handled = true; 
      const string insertText = ")"; 
      var selectionIndex = textBox1.SelectionStart;   
      textBox1.Text = textBox1.Text.Insert(selectionIndex, "("); 
      textBox1.Text = textBox1.Text.Insert(selectionIndex +1, insertText); 
      textBox1.SelectionStart = selectionIndex + insertText.Length; 
     } 
+0

这个完美的作品。感谢Badiparmagi! – Thow

+0

@很高兴帮助! – Badiparmagi