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 and what I want is .
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?
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;
}