Let's say you are writing a Visual Studio add-in that does some stuff with selected text, for example string literals in the code.
It would be very user friendly if the user could just click inside that string literal and add-in would figure it out and select a complete string.
Well, that's just what I had in mind the other day, but I had a hard time finding a code that would do that. It's rare these days that you don't find a code snippet that can speed up your development.
I wrote it myself and this is what I did. I hope I save someone some time with it...
Document document = _applicationObject.ActiveDocument;
TextSelection selection = (TextSelection)document.Selection;
TextPoint cursorTextPoint = selection.ActivePoint;
if (selection.Text.Length > 0)
// some text is selected
startPoint = selection.TopPoint.CreateEditPoint();
endPoint = selection.BottomPoint.CreateEditPoint();
// lets move one char left so we can inspect last character
// nothing is selected
startPoint = cursorTextPoint.CreateEditPoint();
endPoint = cursorTextPoint.CreateEditPoint();
string stopChar = "\"";
// move left selection margin to stopChar or start of line
while (startPoint.GetText(1) != stopChar && !startPoint.AtStartOfLine)
// move right selection margin to stopChar or end of line
while (endPoint.GetText(1) != stopChar && !endPoint.AtEndOfLine)
// compensate for last character
if (!endPoint.AtEndOfLine) endPoint.CharRight(1);
// do we have a valid selection?
if (!startPoint.AtStartOfLine && !endPoint.AtEndOfLine)
string selectedText = startPoint.GetText(endPoint);
// do stuff with selected text
// you can replace selected text like this
// startPoint.ReplaceText(endPoint, "fresh text");
MessageBox.Show("Invalid selection!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);