Forbid to move cursor in RichTextBox past certain position

57 views Asked by At

enter image description here

I am writing a program for entering words by syllable. The logic is, the user is entering part of the phrase (a syllable), and if it's correct it lights out a green color and adds a hyphen in the end, so the user can continue to enter the word. I need to forbid every user input before the hyphen, so he can't move back after he wrote correct syllable. But I am struggling with that part. What I've tried:

private void rtbEnterWord_KeyDown(object sender, KeyEventArgs e)
{
    if (rtbEnterWord.SelectionStart <= this.lastHyphen && e.KeyCode == Keys.Left)
    {
        rtbEnterWord.SelectionStart = this.lastHyphen;
        e.Handled = true; 
    }
}

private void rtbEnterWord_KeyPress(object sender, KeyPressEventArgs e)
{
    if (rtbEnterWord.SelectionStart <= this.lastHyphen)
    {
        e.Handled = true; 
    }
}

And the other variant:

private void rtbEnterWord_TextChanged(object sender, EventArgs e)
{
    if (rtbEnterWord.TextLength <= certainPosition)
    {        
        rtbEnterWord.Text = rtbEnterWord.Text.Remove(0, certainPosition);         
        rtbEnterWord.SelectionStart = rtbEnterWord.Text.Length;
    }
}

Both don't work. What I need to implement, is that hyphen would become a -1 element of the string (if you can say that) so input will be only after that hyphen symbol, everything else before that would be completely ignored like it doesn't exist. It sounds like an easy task but I can't come up with any decent solution.

1

There are 1 answers

0
sherwood On

Here is what I've came up with, after reading manual. Code works as expected and doesn't allow user to move cursor to the left of given position. Also don't forget to add events to control element, in my case RichTextBox1 (in form designer)

 private void rtbEnterWord_MouseDown(object sender, MouseEventArgs e)
 {
    
     int positionToSet = this.lastEnterCharPos; 
     rtbEnterWord.SelectionStart = positionToSet;
     rtbEnterWord.SelectionLength = 0;

    
 }

 private void rtbEnterWord_KeyDown(object sender, KeyEventArgs e)
 {

     
     if (e.KeyCode == Keys.Back)
     {
         if (rtbEnterWord.SelectionStart <= this.lastEnterCharPos)
         {
             e.SuppressKeyPress = true;
         }
     }                 
    
     if (rtbEnterWord.SelectionStart <= this.lastEnterCharPos && e.KeyCode == Keys.Left )
     {                
         e.SuppressKeyPress = true;
       
     }
 }

lastEnterCharPos is a value where I place last hyphen location