简体   繁体   中英

How to detect if cursor position is between certain characters in richtextbox

So I'm trying to make a editor application in Winforms that allows me to have automatic bracket alignment. I currently have a richtextbox that creates a closing bracket when I press the opening bracket.

The next thing I want to do is when my cursor is between the opening and closing brackets and I press enter, that the closing bracket gets places 2 lines further then the opening bracket and that the cursor gets placed one line further with a tab inserted.

My main question is, how to I detect if the cursor is between 2 certain characters? The placement of the closing bracket and cursor is optional.

public void addTabToText()
    {
      int caretPos = myTextBox.SelectionStart; //Get the start position
      if(caretPos != 0 && caretPos!=myTextBox.Text.Length) //if not at the end or start
      {
        if(myTextBox.Text[caretPos-1]=='(' && myTextBox.Text[caretPos]==')'){
          myTextBox.Text = myTextBox.Text.Insert(caretPos, "  ");
          //to change cursor position
          myTextBox.SelectionStart = caretPos + 2; // length of string added 
          myTextBox.SelectionLength = 0;
        }
      }
    }

Here, I'm checking for the previous char and the next char, using the SelectionStart . This you can call from Enter pressed event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM