C# RichTextBox ReadOnly Event

1.8k views Asked by At

I have a read only rich text box and an editable text box. The text from the read only is from the editable. They can't be viewed at the same time. When the user presses a key it hides the read only and then selects that position in the editable.

I would like it to enter the key that was pressed into the editable without playing the error "ding"

I'm thinking that an override of the read only error function would be ideal but i'm not sure what that is.

    private void EditCode(object sender, KeyPressEventArgs e)
    {
        int cursor = txtReadOnly.SelectionStart;
        tabText.SelectedIndex = 0;
        ToggleView(new object(), new EventArgs());
        txtEdit.SelectionStart = cursor;
        txtEdit.Text.Insert(cursor, e.KeyChar.ToString());
    }

Answer:

    private void EditCode(object sender, KeyPressEventArgs e)
    {
        e.Handled = true;
        int cursor = txtCleanCode.SelectionStart;
        tabText.SelectedIndex = 0;
        ToggleView(new object(), new EventArgs());

        txtCode.Text = txtCode.Text.Insert(cursor, e.KeyChar.ToString());

        txtCode.SelectionStart = cursor + 1;
    }

I'll have to make it check if it's a non-control char but that's another deal. Thanks everyone!

2

There are 2 answers

2
SteveFerg On BEST ANSWER

One idea is to make the rich text box editable but canceling out all keys:

private void richtextBox1_KeyDown(object sender, KeyEventArgs e)
{
    // Stop the character from being entered into the control
    e.Handled = true;
    // add any other code here
}
2
TaW On

Here is one way: Check for <Enter> so the user can still use the navigation keys:

private void txtReadOnly_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        e.Handled = true;  // no ding for normal keys in the read-only!
        txtEdit.SelectionStart = txtReadOnly.SelectionStart;
        txtEdit.SelectionLength = txtReadOnly.SelectionLength;
    }
}

No need to fiddle with a cursor. Make sure to have:

txtEdit.HideSelection = false;

and maybe also

txtReadOnly.HideSelection = false;

Obviously to keep the two synchronized :

private void txtEdit_TextChanged(object sender, EventArgs e)
{
    txtReadOnly.Text = txtEdit.Text;
}

You will need o decide on some way fo r the user to return from editing to viewing. Escape should be reserved for aborting the edit! Maybe Control-Enter?