Code Snippet
private void richTextBox1_SelectionChanged(object sender, EventArgs e)
{
// Only allows to select from 20th character to 30th character
int allowedStartIndex = 20;
int allowedEndIndex = 30;
int selectionStart = richTextBox1.SelectionStart;
int selectionEnd = richTextBox1.SelectionStart + richTextBox1.SelectionLength;
// starts at 15
if (selectionStart < allowedStartIndex)
{
// ends at 18
if (selectionEnd < allowedStartIndex)
{
richTextBox1.SelectionLength = 0;
}
// ends at 25
else if (selectionEnd <= allowedEndIndex)
{
richTextBox1.SelectionStart = allowedStartIndex;
richTextBox1.SelectionLength = selectionEnd - allowedStartIndex;
}
// ends at 31
else //if (selectionEnd > allowedEndIndex)
{
richTextBox1.SelectionStart = allowedStartIndex;
richTextBox1.SelectionLength = allowedEndIndex - allowedStartIndex;
}
}
// starts at 25
else if (selectionStart <= allowedEndIndex)
{
// ends at 31
if (selectionEnd > allowedEndIndex)
{
richTextBox1.SelectionLength = allowedEndIndex - selectionStart;
}
// ends at 18
else if (selectionEnd < allowedStartIndex)
{
richTextBox1.SelectionLength = selectionStart - allowedStartIndex;
}
}
// starts at 35
else // if(selectionStart > allowedEndIndex)
{
// end at 31
if (selectionEnd > allowedEndIndex)
{
richTextBox1.SelectionLength = 0;
}
// ends at 28
else if (selectionEnd >= allowedStartIndex)
{
richTextBox1.SelectionStart = allowedEndIndex;
richTextBox1.SelectionLength = allowedEndIndex - selectionEnd;
}
// ends at 18
else // if (selectionEnd < allowedStartIndex)
{
richTextBox1.SelectionStart = allowedEndIndex;
richTextBox1.SelectionLength = allowedEndIndex - allowedStartIndex;
}
}
}