/// <summary> /// return a TextPointer positioned before a specified position on the line. /// If the position exceeds the end of the line, either pad the line with /// blanks or set the position to the last char on the line. /// </summary> /// <param name="Doc"></param> /// <param name="Pointer"></param> /// <param name="Position"></param> /// <param name="Pad"></param> /// <returns></returns> public static TextPointer SetPositionOnLine( this TextPointer Pointer, FlowDocument Doc, int Position, bool Pad = false) { TextPointer tp = Pointer.GetLineStartPosition(0); int pos = Position; // make sure length of the line can accomodate the position. string lineText = Pointer.GetLineText(Doc, 0, ""); if (pos > (lineText.Length - 1)) { if (Pad == false) { pos = lineText.Length - 1; } else { Pointer.PadLineToLength(Doc, pos + 1); lineText = Pointer.GetLineText(Doc); } } // position to the last char on the line. if (lineText.Length == (pos + 1)) { tp = Pointer.GetLineEndPosition(Doc); } // advance a char at a time from the start of the line. else { for (int ix = 0; ix < pos; ++ix) { var nextTp = tp.GetNextInsertionPosition(LogicalDirection.Forward); if (nextTp != null) { tp = nextTp; } else { break; } } } return(tp); }