How to change the separator of a C# TextBox when I double click to select a word?

70 Views Asked by At

When I use a C# TextBox as an input box, I found it hard to quickly select a word by doubleclicking on then text, because it sometimes selects brackets and other characters. For example, when I double click on var3, it selects enter image description here and what I want is enter image description here.

I tried adding doubleclick callback, but it seems be handled after default handler, and I don't know where user actually clicked, this also messes up the dragging operation after doubleclick to select multiple words.

Is there a easy way to redefine the separator chars for word selection?

2

There are 2 best solutions below

0
Tim Schmelter On BEST ANSWER

You can handle the DoubleClick event and modify the SelectionStart and SelectionLength properties accordingly. Trim the delimiters at the start and end:

private static readonly char[] Delimiters = { ' ', '(', ')', ',', ';', '.', '-', ':', '[', ']' }; // and so on...

private void textBox1_DoubleClick(object sender, EventArgs e)
{
    TextBox txt = (TextBox)sender;
    string selectedText = txt.SelectedText;
    int selectStartOld = txt.SelectionStart;
    int selectLengthOld = txt.SelectionLength;
    int selectStartNew = selectStartOld;
    int selectLengthNew = selectLengthOld;
    bool inText = false;

    for (int i = 0; i < selectedText.Length; i++)
    {
        if (!inText && Delimiters.Contains(selectedText[i]))
        {
            // TrimStart
            selectStartNew++;
            selectLengthNew--;
        }
        else if (inText && Delimiters.Contains(selectedText[i]))
        {
            // TrimEnd
            selectLengthNew--;
        }
        else
        {
            inText = true;
        }
    }

    txt.SelectionStart = selectStartNew;
    txt.SelectionLength = selectLengthNew;
} 
1
jason.kaisersmith On

My answer is similar to Tim's but I just focus on StartsWith and EndsWith.
So you still need to handle the doubleclick event of the button.

//Define as required
private static readonly string[] operators = { "(", ")", "[", "]", "{", "}", ",", ", ", ".", ", " }; 

private void textbox1_DoubleClick(object sender, EventArgs e)
{        
    if (operators.Any(x => textbox1.SelectedText.EndsWith(x)))
    {
        textbox1.SelectionStart = textbox1.SelectionStart;
        textbox1.SelectionLength = textbox1.SelectionLength - 1;
    }
    else if (operators.Any(x => textbox1.SelectedText.StartsWith(x)))
    {
        textbox1.SelectionStart = textbox1.SelectionStart + 1;
        textbox1.SelectionLength = textbox1.SelectionLength - 1;
    }
}