Thow Thow - 27 days ago 14
C# Question

Can't get automatic closing brackets in a TextBox

I'm making an app with a basic code editor for myself.
When creating auto brackets I ran into a problem.
When my cursor is in line 4 of the textbox and I press '(' It moves the '(' to line 1 of the textbox and it adds a ')' in line 4.

This is my code:

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

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


editorTB is my richtextbox1 control.

I hope someone can help me resolve the problem. Thanks in advance!

Answer

Try the following in your Control.KeyPress event:

    if (e.KeyChar == '(')
    {
        e.Handled = true;
        editorTB.AppendText("()");
    }