Search code examples
c#textbox.net-4.8windows-dev-center

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


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?


Solution

  • 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;
    }