public static void GenerateClipBoardData(DataObjectCopyingEventArgs e, TextSelection selection) { string str; using (MemoryStream stream = new MemoryStream()) { TextRange range = new TextRange(selection.Start, selection.End); range.ClearAllProperties(); range.Save(stream, DataFormats.Xaml, true); stream.Flush(); stream.Position = 0L; using (StreamReader reader = new StreamReader(stream)) { str = reader.ReadToEnd(); } } if (!string.IsNullOrEmpty(str)) { string str2 = ReplaceControls.ReplaceGUIWithClipboardControl(str, selection.Start, selection.End); if (!string.IsNullOrEmpty(str2) && (str2 != str)) { e.DataObject.SetData(BamaDataFormat, str2); } } }
public override void OnValueChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) { // If we don't have a textBox, return if (!(sender is RichTextBox richTextBox)) { return; } // Get the search text var searchText = e.NewValue as string; // Get the textRange from richTextbox var textRange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd); // Clear seleted text in textbox textRange.ClearAllProperties(); // If search text is empty... if (string.IsNullOrEmpty(searchText)) { return; } var foundRange = FindTextInRange(textRange, searchText); if (foundRange == null) { return; } foundRange.ApplyPropertyValue(TextElement.FontFamilyProperty, new FontFamily(new Uri("pack://application:,,,/"), "./Fonts/#Lato Bold")); foundRange.ApplyPropertyValue(TextElement.ForegroundProperty, (SolidColorBrush)Application.Current.FindResource("WordOrangeBrush") ?? new SolidColorBrush(Colors.Orange)); }
private void SetSessionRoot_Click(object sender, RoutedEventArgs e) { var selectedItem = treeUiPath.SelectedItem as UiTreeNode; if (selectedItem == null) { return; } int nNodeCount = 1; var pParent = selectedItem.Parent; while (pParent != null) { nNodeCount++; pParent = pParent.Parent; } string sessionRootPath = HighlightPath(nNodeCount, false); var textPath = new TextRange(rtbXPath.Document.ContentStart, rtbXPath.Document.ContentEnd).Text; var pos1 = rtbXPath.Document.ContentStart.GetPositionAtOffset(1, LogicalDirection.Forward); int nPos2 = textPath.IndexOf(sessionRootPath) + sessionRootPath.Length; RootSessionPath = textPath.Substring(0, nPos2); var pos2 = rtbXPath.Document.ContentStart.GetPositionAtOffset(nPos2 + 2, LogicalDirection.Forward); var textRange = new TextRange(pos1, pos2); textRange.ClearAllProperties(); textRange.ApplyPropertyValue(TextElement.BackgroundProperty, Brushes.LightGray); AppInsights.LogEvent("SetSessionRoot_Click"); }
private void rtbCode_TextChanged(object sender, TextChangedEventArgs e) { if (formatting) { return; } formatting = true; TextRange textRange = new TextRange(rtbCode.Document.ContentStart, rtbCode.Document.ContentEnd); textRange.ClearAllProperties(); List <Tuple <TextPointer, TextPointer> > delimiters = new List <Tuple <TextPointer, TextPointer> >(); foreach (Match match in split.Matches(textRange.Text)) { delimiters.Add(new Tuple <TextPointer, TextPointer>( textRange.Start.GetPositionAtOffset(match.Index), textRange.Start.GetPositionAtOffset(match.Index + match.Length) )); } new TextRange(textRange.Start, delimiters.Count > 0 ? delimiters[0].Item1 : textRange.End) .ApplyPropertyValue(TextElement.BackgroundProperty, lightYellow); for (int i = 0; i < delimiters.Count; i++) { new TextRange(delimiters[i].Item2, delimiters.Count > i + 1 ? delimiters[i + 1].Item1 : textRange.End) .ApplyPropertyValue(TextElement.BackgroundProperty, i % 2 == 0 ? lightRed : lightGreen); } NoWrap(rtbCode); formatting = false; }
private void Button_Click_1(object sender, RoutedEventArgs e) { OpenFileDialog openFile1 = new OpenFileDialog(); openFile1.FileName = "Document"; openFile1.DefaultExt = "*.*"; openFile1.Filter = "All Files|*.*|Rich Text Format|*.rtf|Word Document|*.docx|Word 97-2003 Document|*.doc"; if (openFile1.ShowDialog() == true) { var range = new TextRange(RichText.Document.ContentStart, RichText.Document.ContentEnd); using (var fStream = new FileStream(openFile1.FileName, FileMode.OpenOrCreate)) { // load as RTF, text is formatted range.Load(fStream, DataFormats.Rtf); fStream.Close(); pth = openFile1.FileName; } // clear the formatting, turning into plain text range.ClearAllProperties(); } save.IsEnabled = false; savem.IsEnabled = false; }
private void ChatMessageHelper(string message) { // Remove opponent typing notification if one is posted if (opponentTypingTR != null && !opponentTypingTR.IsEmpty) { opponentTypingTimer.Change(Timeout.Infinite, Timeout.Infinite); chatKeyCount = 0; opponentTypingTR.Text = ""; } // Post an oppononent name timestamp header to the message box string oppHeaderText = String.Format("{0} ({1})\n", opponentName, DateTime.Now.ToString("h:mm tt").ToLower()); TextRange oppHeader = PostChatBoxHeader(oppHeaderText, 14.0, FontStyles.Normal, FontWeights.ExtraBold, Brushes.Red); // Indent and add the received message underneath the header TextRange oppMessage = new TextRange(oppHeader.End, oppHeader.End); oppMessage.Start.Paragraph.Margin = new Thickness(10, 0, 0, 0); oppMessage.Text = message + "\n\n"; oppMessage.ClearAllProperties(); oppMessage.End.Paragraph.Margin = new Thickness(0, 0, 0, 0); if (soundOffCheckBox.IsChecked == false) { chatSound.Play(); } }
void ClearProperties() { var documentRange = new TextRange(this.Document.ContentStart, this.Document.ContentEnd); documentRange.ClearAllProperties(); }
//Protected Overrides Sub OnRender(drawingContext As System.Windows.Media.DrawingContext) // drawingContext.PushClip(New RectangleGeometry(New Rect(0, 0, Me.ActualWidth, Me.ActualHeight))) // drawingContext.DrawRectangle(Brushes.White, Nothing, New Rect(0, 0, Me.ActualWidth, Me.ActualHeight)) // If Me.Text.Trim = "" Then Return // Dim edtText = Me.Text.ToLower // Dim flowDir As FlowDirection = Windows.FlowDirection.LeftToRight // If Globalization.CultureInfo.CurrentCulture.TextInfo.IsRightToLeft Then // flowDir = Windows.FlowDirection.RightToLeft // End If // Dim fmtText As New FormattedText(edtText, Globalization.CultureInfo.CurrentCulture, // flowDir, // New Typeface(Me.FontFamily.Source), // Me.FontSize, // Brushes.Black) With {.Trimming = TextTrimming.None //} // //既存クラスの検索 // //キーワードの検索 // If keyWords IsNot Nothing Then // Tasks.Parallel.ForEach(keyWords.Matches(edtText).Cast(Of Match), // Sub(keyWordMatch As Match) // Dim st = edtText.IndexOf(keyWordMatch.ToString.ToLower) // fmtText.SetForegroundBrush(Brushes.Blue, st, keyWordMatch.ToString.Length) // End Sub) // End If // //文字列の検索 // Tasks.Parallel.ForEach(stringMatch.Matches(edtText).Cast(Of Match), // Sub(keyWordMatch As Match) // Dim st = edtText.IndexOf(keyWordMatch.ToString.ToLower) // fmtText.SetForegroundBrush(Brushes.Red, st, keyWordMatch.ToString.Length) // End Sub) // drawingContext.DrawText(fmtText, New Point(Me.Margin.Left, Me.Margin.Top)) // MyBase.OnRender(drawingContext) //End Sub private void OnTextChangedPrivate(object sender, TextChangedEventArgs e) { if (this.Document == null) { return; } var docRange = new TextRange(this.Document.ContentStart, this.Document.ContentEnd); docRange.ClearAllProperties(); var navigator = this.Document.ContentStart; while (navigator.CompareTo(this.Document.ContentEnd) < 0) { var context = navigator.GetPointerContext(LogicalDirection.Backward); if (context == TextPointerContext.ElementStart && navigator.Parent.GetType() == typeof(Run)) { CheckWordsInRun(navigator.Parent as Run); } navigator = navigator.GetNextContextPosition(LogicalDirection.Forward); } FormatText(); }
private void TextChangedEventHandler(object sender, TextChangedEventArgs e) { // Nothing here, then get the hell out of here! if (TextInput.Document == null) { return; } if (HL_BLOCK) { return; } HL_BLOCK = true; // Clear all previos settings! They can only spook things up! var documentRange = new TextRange(TextInput.Document.ContentStart, TextInput.Document.ContentEnd); documentRange.ClearAllProperties(); var TXT = documentRange.Text; var recognizedas = ""; #if AlwaysNIL recognizedas = "NIL"; #else #endif if (recognizedas != "") { Highlights.Algemeen.HLDrivers[recognizedas].Highlight(TextInput, TXT); } HL_BLOCK = false; }
private static string GetInputText(RichTextBox rtb) { TextRange documentRange = new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd); documentRange.ClearAllProperties(); return(documentRange.Text.Substring(0, documentRange.Text.Length - 2)); }
public void SetText(System.Windows.Documents.FlowDocument document, string text) { try { //if the text is null/empty clear the contents of the RTB. If you were to pass a null/empty string //to the TextRange.Load method an exception would occur. if (String.IsNullOrEmpty(text)) { document.Blocks.Clear(); } else { TextRange tr = new TextRange(document.ContentStart, document.ContentEnd); tr.ClearAllProperties(); text = System.Text.RegularExpressions.Regex.Replace(text, "&#x(0?[0-8B-F]|1[0-9A-F]|7F);", ""); using (MemoryStream ms = new MemoryStream(ASCIIEncoding.UTF8.GetBytes(text))) { tr.Load(ms, DataFormats.Xaml); } } } catch { //throw new InvalidDataException( "Data provided is not in the correct Xaml format." ); System.Diagnostics.Debug.WriteLine("Data provided is not in the correct Xaml format. Text is : "); System.Diagnostics.Debug.WriteLine(text); } }
/// <summary> /// Clears the selection in the RichTextBox leaving the cursor position where it was. /// </summary> /// <param name="rtb"></param> /// <param name="text"></param> /// <param name="startIndex"></param> /// <param name="setFocus"></param> public static int SelectFind(this RichTextBox rtb, string text, int startIndex = 0, bool setFocus = false) { var textRange = new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd); // Clear previous selection if there was one. rtb.Selection.Select(textRange.Start, textRange.Start); textRange.ClearAllProperties(); var index = textRange.Text.IndexOf(text, startIndex, StringComparison.OrdinalIgnoreCase); if (index > -1) { var textPointerStart = textRange.Start.GetPositionAtOffset(index); var textPointerEnd = textRange.Start.GetPositionAtOffset(index + text.Length); var textRangeSelection = new TextRange(textPointerStart, textPointerEnd); textRangeSelection.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold); rtb.Selection.Select(textRangeSelection.Start, textRangeSelection.End); if (setFocus) { rtb.Focus(); } } return(index); }
private async Task UpdateParagraph(Paragraph p) { if (p == null) { return; } /// Updates a Specific Paragraph List <Tuple <TextPointer, TextPointer, Color> > Colorizer = new List <Tuple <TextPointer, TextPointer, Color> >(); TextRange pText = new TextRange(p.ContentStart, p.ContentEnd); pText.ClearAllProperties(); foreach (KeyValuePair <string, Color> obj in dict) { foreach (Match i in Regex.Matches(pText.Text, obj.Key)) { Colorizer.Add(new Tuple <TextPointer, TextPointer, Color>(p.ContentStart.GetPositionAtOffset(i.Index + 1), p.ContentStart.GetPositionAtOffset(i.Index + i.Length + 1), obj.Value)); } } foreach (Tuple <TextPointer, TextPointer, Color> i in Colorizer) { TextRange pTextC = new TextRange(i.Item1, i.Item2); pTextC.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(i.Item3)); } Editor.UpdateLayout(); }
public void Find(string _find) { TextRange documentRange = new TextRange(this.Document.ContentStart, this.Document.ContentEnd); documentRange.ClearAllProperties(); _trs.Clear(); TextPointer navigator = this.Document.ContentStart; while (navigator.CompareTo(this.Document.ContentEnd) < 0) { TextPointerContext context = navigator.GetPointerContext(LogicalDirection.Backward); if (context == TextPointerContext.ElementStart && navigator.Parent is Run) { Run r = ((Run)navigator.Parent); string text = r.Text; Match m = Regex.Match(text, _find); if (m.Success) { TextPointer tp = r.ElementStart; TextRange range = new TextRange(tp.GetPositionAtOffset(m.Index + 1), tp.GetPositionAtOffset(m.Index + m.Length + 1)); _trs.Add(range); } } navigator = navigator.GetNextContextPosition(LogicalDirection.Forward); } foreach (TextRange range in _trs) { range.ApplyPropertyValue(TextElement.BackgroundProperty, new SolidColorBrush(Colors.Yellow)); } FindNext(); }
//get the text, separate each word, check for first char if its @ or #, if it's, match against rules, then format else do nothing private void TextChangedEventHandler(object sender, TextChangedEventArgs e) { if (Text_Input.Document == null) { return; } TextRange documentRange = new TextRange(Text_Input.Document.ContentStart, Text_Input.Document.ContentEnd); documentRange.ClearAllProperties(); TextPointer navigator = Text_Input.Document.ContentStart; //get the start of the input //inplace to remove invisible tags and match char position with text position, stackoverflow.com/questions/2565783/wpf-flowdocument-absolute-character-position while (navigator.CompareTo(Text_Input.Document.ContentEnd) < 0) { TextPointerContext context = navigator.GetPointerContext(LogicalDirection.Backward); if (context == TextPointerContext.ElementStart && navigator.Parent is Run) { checkWords((Run)navigator.Parent); } navigator = navigator.GetNextContextPosition(LogicalDirection.Forward); } Format(words); }
private void Input_TextChanged(object sender, TextChangedEventArgs e) { if (string.IsNullOrEmpty(RegexString) || string.IsNullOrEmpty(InputString)) { return; } InputBox.TextChanged -= Input_TextChanged; try { Match m = Regex.Match(InputString, RegexString); string output = string.Empty; dataList.Clear(); m_tags.Clear(); TextRange documentRange = new TextRange(InputBox.Document.ContentStart, InputBox.Document.ContentEnd); documentRange.ClearAllProperties(); //InputTreeView.ItemsSource = GetTreeItem(InputBox.Document); CheckWordsInFlowDocument(InputBox.Document); for (int i = 0; i < m_tags.Count; i++) { TextRange range = new TextRange(m_tags[i].StartPosition, m_tags[i].EndPosition); range.ApplyPropertyValue(TextElement.BackgroundProperty, i % 2 == 0 ? highlightBackground1 : highlightBackground2); } OutputString = DateTime.Now.ToString("HH:mm:ss") + "\r\n共" + dataList.Count + "个匹配项"; } catch (Exception ex) { OutputString = DateTime.Now.ToString("HH:mm:ss") + "\r\n" + ex.ToString(); } InputBox.TextChanged += Input_TextChanged; }
private static void ColorizeMaxElement(this RichTextBox richBox, float[,] arr) { FindMaxIndexs(arr, out int iMax, out int jMax); string maxElement = arr[iMax, jMax].ToString(); Paragraph paragraph = richBox.Document.Blocks.FirstBlock as Paragraph; TextRange tRange = new TextRange(paragraph.ContentStart, paragraph.ContentEnd); tRange.ClearAllProperties(); List <TextRange> selections = new List <TextRange>(); string text = tRange.Text; int index = text.IndexOf(maxElement, StringComparison.InvariantCultureIgnoreCase); while (index++ >= 0) { var textPointerStart = paragraph.ContentStart.GetPositionAtOffset(index); var textPointerEnd = paragraph.ContentStart.GetPositionAtOffset(index + maxElement.Length); selections.Add(new TextRange(textPointerStart, textPointerEnd)); if (index + maxElement.Length >= text.Length) { break; } index = text.IndexOf(maxElement, index + maxElement.Length, StringComparison.CurrentCultureIgnoreCase); } foreach (var selection in selections) { selection.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.DarkViolet); } }
private void TextInput_TextChanged(object sender, TextChangedEventArgs e) { if (textInput.Document == null) { return; } TextRange documentRange = new TextRange(textInput.Document.ContentStart, textInput.Document.ContentEnd); documentRange.ClearAllProperties(); TextPointer navigator = textInput.Document.ContentStart; while (navigator.CompareTo(textInput.Document.ContentEnd) < 0) { TextPointerContext context = navigator.GetPointerContext(LogicalDirection.Backward); if (context == TextPointerContext.ElementStart && navigator.Parent is Run) { try { CheckWordsInRun((Run)navigator.Parent); } catch { } } navigator = navigator.GetNextContextPosition(LogicalDirection.Forward); } Format(); }
private void rtbInput_TextChanged(object sender, TextChangedEventArgs e) { TextRange textRange = new TextRange(rtbInput.Document.ContentStart, rtbInput.Document.ContentEnd); textRange.ClearAllProperties(); NoWrap(rtbInput); }
internal static bool PasteContentData(InputBox inputBox, IDataObject iDataObject) { TextData data = TryGetText(iDataObject); if (!data.ContainsData) { if (iDataObject.GetDataPresent(DataFormats.Bitmap, true)) { inputBox.Paste(iDataObject); return(true); } return(false); } inputBox.TempFlowDocument.Blocks.Clear(); TextRange range = null; if (data.Format == BamaDataFormat) { object obj2 = XamlReader.Parse(data.Data); if (obj2 is Block) { inputBox.TempFlowDocument.Blocks.Add(obj2 as Block); } else if (obj2 is Inline) { Span span = new Span(inputBox.TempFlowDocument.ContentStart, inputBox.TempFlowDocument.ContentEnd) { Inlines = { obj2 as Span } }; } range = new TextRange(inputBox.TempFlowDocument.ContentStart, inputBox.TempFlowDocument.ContentEnd); range.ClearAllProperties(); inputBox.Selection.Text = ""; Span newspan = new Span(inputBox.Selection.Start, inputBox.Selection.End); ReplaceControls.AddBlocksToSpan(inputBox.TempFlowDocument, newspan); inputBox.CaretPosition = newspan.ElementEnd.GetInsertionPosition(LogicalDirection.Forward); } else { range = new TextRange(inputBox.TempFlowDocument.ContentStart, inputBox.TempFlowDocument.ContentEnd); using (MemoryStream stream = new MemoryStream()) { using (StreamWriter writer = new StreamWriter(stream)) { writer.Write(data.Data); writer.Flush(); stream.Position = 0L; range.Load(stream, data.Format); } } range.ClearAllProperties(); inputBox.Selection.Text = ""; Span span3 = new Span(inputBox.Selection.Start, inputBox.Selection.End); ReplaceControls.AddBlocksToSpan(inputBox.TempFlowDocument, span3); inputBox.CaretPosition = span3.ElementEnd.GetInsertionPosition(LogicalDirection.Forward); } inputBox.TempFlowDocument.Blocks.Clear(); return(true); }
public void FormatCurrentLine() { /*These checks are necessary to invoke FormatCurrentLinefunction as it uses Caret related properties * and is included in TextChange event handler. So, if you need to execute this function elsewhere, include these checks. * * if (rtb1.Document == null) * return; * if (rtb1.CaretPosition.Paragraph == null) * return; * if (rtb1.CaretPosition.Paragraph.Inlines.FirstInline == null) * return; */ int i; string s; Run r; TextRange paragraphRange = new TextRange(rtb1.CaretPosition.Paragraph.ContentStart, rtb1.CaretPosition.Paragraph.ContentEnd); paragraphRange.ClearAllProperties(); r = (Run)(rtb1.CaretPosition.Paragraph.Inlines.FirstInline); if (r.Text == null) { return; } s = r.Text; registerMatches = register.Matches(s); digitMatches = digit.Matches(s); keywordMatches = keyword.Matches(s); commentMatches = comment.Matches(s); for (i = 0; i <= registerMatches.Count - 1; i++) { TextRange temp = new TextRange(r.ContentStart.GetPositionAtOffset(registerMatches[i].Index, LogicalDirection.Forward), r.ContentStart.GetPositionAtOffset(registerMatches[i].Index + registerMatches[i].Length, LogicalDirection.Forward)); registerAllMatches.Add(temp); } for (i = 0; i <= digitMatches.Count - 1; i++) { TextRange temp = new TextRange(r.ContentStart.GetPositionAtOffset(digitMatches[i].Index, LogicalDirection.Forward), r.ContentStart.GetPositionAtOffset(digitMatches[i].Index + digitMatches[i].Length, LogicalDirection.Forward)); digitAllMatches.Add(temp); } for (i = 0; i <= keywordMatches.Count - 1; i++) { TextRange temp = new TextRange(r.ContentStart.GetPositionAtOffset(keywordMatches[i].Index, LogicalDirection.Forward), r.ContentStart.GetPositionAtOffset(keywordMatches[i].Index + keywordMatches[i].Length, LogicalDirection.Forward)); keywordAllMatches.Add(temp); } for (i = 0; i <= commentMatches.Count - 1; i++) { TextRange temp = new TextRange(r.ContentStart.GetPositionAtOffset(commentMatches[i].Groups["comment"].Index, LogicalDirection.Forward), r.ContentStart.GetPositionAtOffset(commentMatches[i].Groups["comment"].Index + commentMatches[i].Groups["comment"].Length, LogicalDirection.Forward)); commentAllMatches.Add(temp); } Format(); }
private void MainRichTextBox_PreviewKeyDown(object sender, KeyEventArgs e) { OneChange = true; if (Keyboard.IsKeyDown(Key.Back)) { Back = true; } else { Back = false; } if (Keyboard.IsKeyDown(Key.Delete)) { Del = true; } else { Del = false; } if ((Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift)) && e.Key == Key.Tab) { string ss = new TextRange(MainRichTextBox.CaretPosition.GetLineStartPosition(0), MainRichTextBox.CaretPosition).Text; if (ss[ss.Length - 1] == '\t') { MainRichTextBox.CaretPosition = MainRichTextBox.CaretPosition.GetPositionAtOffset(-1, LogicalDirection.Backward); MainRichTextBox.CaretPosition.DeleteTextInRun(1); MainRichTextBox.CaretPosition = MainRichTextBox.CaretPosition.GetPositionAtOffset(0, LogicalDirection.Forward); } Dispatcher.BeginInvoke( DispatcherPriority.ContextIdle, new Action(delegate() { MainRichTextBox.Focus(); })); e.Handled = true; return; } else if (e.Key == Key.Tab) { TextRange documentRange = new TextRange(MainRichTextBox.Document.ContentStart, MainRichTextBox.Document.ContentEnd); documentRange.ClearAllProperties(); MainRichTextBox.CaretPosition = MainRichTextBox.CaretPosition.GetPositionAtOffset(0, LogicalDirection.Forward); MainRichTextBox.CaretPosition.InsertTextInRun("\t"); //string textRange = new TextRange(MainRichTextBox.Document.ContentStart, MainRichTextBox.Document.ContentEnd).Text; //MainRichTextBox.CaretPosition = MainRichTextBox.CaretPosition.GetPositionAtOffset(0, LogicalDirection.Forward); //MainRichTextBox.CaretPosition.InsertTextInRun("\t"); //textRange = new TextRange(MainRichTextBox.Document.ContentStart, MainRichTextBox.Document.ContentEnd).Text; Dispatcher.BeginInvoke( DispatcherPriority.ContextIdle, new Action(delegate() { MainRichTextBox.Focus(); })); e.Handled = true; return; } }
private void textEditorRB_TextChange(object sender, TextChangedEventArgs e) { Dispatcher.Invoke(() => { if (textEditorRB.Document == null) { return; } //first clear all the formats TextRange documentRange = new TextRange(textEditorRB.Document.ContentStart, textEditorRB.Document.ContentEnd); documentRange.ClearAllProperties(); textEditorRB.TextChanged -= this.textEditorRB_TextChange; string pattern = @"([^\W_]+[^\s,.]*)"; TextPointer pointer = textEditorRB.Document.ContentStart; while (pointer.CompareTo(textEditorRB.Document.ContentEnd) < 0) { if (pointer.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text) { string textRun = pointer.GetTextInRun(LogicalDirection.Forward); MatchCollection matches = Regex.Matches(textRun, pattern, options); foreach (Match match in matches) { try { TextPointer start = pointer.GetPositionAtOffset(match.Index); TextRange wordRange = new TextRange(start, start.GetPositionAtOffset(match.Length)); if (KeyWordDetector.IsKeyword(wordRange.Text, out SolidColorBrush color)) { wordRange.ApplyPropertyValue(TextElement.ForegroundProperty, color); wordRange.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold); } else { wordRange.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Normal); wordRange.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.White); } } catch (Exception ex) { _ = MessageBox.Show(ex.ToString()); } } } pointer = pointer.GetNextContextPosition(LogicalDirection.Forward); } textEditorRB.TextChanged += this.textEditorRB_TextChange; }); //}).Start(); }
public void ClearFormatting() { RichTextBox rtb = ((RichTextBox)tabControl.SelectedContent); if (rtb != null) { TextRange selectedRange = rtb.Selection; selectedRange.ClearAllProperties(); } }
public void FormatWholeDocument() { int i; string s; TextPointer navigator; TextPointerContext context; Run r; TextRange documentRange = new TextRange(rtb1.Document.ContentStart, rtb1.Document.ContentEnd); //Make a textRange document point to the entire document documentRange.ClearAllProperties(); //Clears all formatting, so all all inlines within a paragraph are converted to a single inline but all paragraphs are kept navigator = rtb1.Document.ContentStart; while (navigator.CompareTo(rtb1.Document.ContentEnd) < 0) { context = navigator.GetPointerContext(LogicalDirection.Backward); if (context == TextPointerContext.ElementStart && navigator.Parent is Run) { r = (Run)navigator.Parent; s = r.Text; registerMatches = register.Matches(s); digitMatches = digit.Matches(s); keywordMatches = keyword.Matches(s); commentMatches = comment.Matches(s); for (i = 0; i <= registerMatches.Count - 1; i++) { TextRange temp = new TextRange(r.ContentStart.GetPositionAtOffset(registerMatches[i].Index, LogicalDirection.Forward), r.ContentStart.GetPositionAtOffset(registerMatches[i].Index + registerMatches[i].Length, LogicalDirection.Forward)); registerAllMatches.Add(temp); } for (i = 0; i <= digitMatches.Count - 1; i++) { TextRange temp = new TextRange(r.ContentStart.GetPositionAtOffset(digitMatches[i].Index, LogicalDirection.Forward), r.ContentStart.GetPositionAtOffset(digitMatches[i].Index + digitMatches[i].Length, LogicalDirection.Forward)); digitAllMatches.Add(temp); } for (i = 0; i <= keywordMatches.Count - 1; i++) { TextRange temp = new TextRange(r.ContentStart.GetPositionAtOffset(keywordMatches[i].Index, LogicalDirection.Forward), r.ContentStart.GetPositionAtOffset(keywordMatches[i].Index + keywordMatches[i].Length, LogicalDirection.Forward)); keywordAllMatches.Add(temp); } for (i = 0; i <= commentMatches.Count - 1; i++) { TextRange temp = new TextRange(r.ContentStart.GetPositionAtOffset(commentMatches[i].Groups["comment"].Index, LogicalDirection.Forward), r.ContentStart.GetPositionAtOffset(commentMatches[i].Groups["comment"].Index + commentMatches[i].Groups["comment"].Length, LogicalDirection.Forward)); commentAllMatches.Add(temp); } } navigator = navigator.GetNextContextPosition(LogicalDirection.Forward); } Format(); }
private void ClearDocumentFormatting() /* Remove all current formatting properties */ { /* Local Variables */ TextRange docRange; /* Text range obeject containing the text of the entire document */ /* / Local Variables */ docRange = new TextRange(Editor.Document.ContentStart, Editor.Document.ContentEnd); docRange.ClearAllProperties(); inMultiLineComment = false; /* Reset checker for multi-line comments */ }
/// <summary> /// Clears all formatting from the text /// </summary> public static void ClearAllFormatting(this RichTextBox rtb) { if (rtb == null) { throw new ArgumentNullException(nameof(rtb)); } TextRange txtRange = new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd); txtRange.ClearAllProperties(); }
private string HighlightPath(int nNodeCount, bool bHighlight) { var tr = new TextRange(rtbXPath.Document.ContentStart, rtbXPath.Document.ContentEnd); string pathText = tr.Text; if (string.IsNullOrEmpty(pathText)) { return(null); } string xpath = pathText; int nIndex1 = 0; int nIndex2 = 0; for (int node = 0; node < nNodeCount; node++) { int Len1 = xpath.Length; xpath = RemoveFirstNode(xpath); nIndex1 = nIndex2 + 1; nIndex2 += (Len1 - xpath.Length); } if (nIndex2 < nIndex1) { return(null); } if (bHighlight == true) { tr.ClearAllProperties(); if (RootSessionPath != null && pathText.Contains(RootSessionPath) == true) { var posRoot1 = rtbXPath.Document.ContentStart.GetPositionAtOffset(1, LogicalDirection.Forward); var posRoot2 = rtbXPath.Document.ContentStart.GetPositionAtOffset(RootSessionPath.Length + 2, LogicalDirection.Forward); var trRoot = new TextRange(posRoot1, posRoot2); trRoot.ApplyPropertyValue(TextElement.BackgroundProperty, Brushes.LightGray); } if (nNodeCount > 0) { var pos1 = rtbXPath.Document.ContentStart.GetPositionAtOffset(nIndex1 + 1, LogicalDirection.Forward); var pos2 = rtbXPath.Document.ContentStart.GetPositionAtOffset(nIndex2 + 2, LogicalDirection.Forward); tr = new TextRange(pos1, pos2); tr.ApplyPropertyValue(TextElement.BackgroundProperty, Brushes.LightBlue); } } return(pathText.Substring(nIndex1, nIndex2 - nIndex1)); //excluding leading quote }
// rest any validation colors in the EditTextBox private void ResetEditTextBox() { // get the text TextRange textRange = new TextRange( // TextPointer to the start of content in the RichTextBox. EditTextBox.Document.ContentStart, // TextPointer to the end of content in the RichTextBox. EditTextBox.Document.ContentEnd ); // clear all formatting - when user is editing textRange.ClearAllProperties(); }
public static Paragraph scriptParagraph = new Paragraph(); //RichTextBox /// <summary> /// Script RichTextBox Edited /// </summary> // Current RichTextBox Text public static String GetScriptRichTextBoxContents(MainWindow mainwindow) { // Select All Text TextRange textRange = new TextRange( mainwindow.rtbScriptView.Document.ContentStart, mainwindow.rtbScriptView.Document.ContentEnd ); // Remove Formatting textRange.ClearAllProperties(); // Return Text return(textRange.Text); }