Edit Rich Text with RichTextBox : RichTextBox « Windows Presentation Foundation « C# / CSharp Tutorial






using Microsoft.Win32;
using System;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;

    public class MainClass : Window
    {
        RichTextBox txtbox = new RichTextBox();
        [STAThread]
        public static void Main()
        {
            Application app = new Application();
            app.Run(new MainClass());
        }
        public MainClass()
        {
            txtbox.VerticalScrollBarVisibility = ScrollBarVisibility.Auto;
            Content = txtbox;
            txtbox.Focus();
        }
        protected override void OnPreviewTextInput(TextCompositionEventArgs args)
        {
            if (args.ControlText.Length > 0 && args.ControlText[0] == '\x0F')
            {
                OpenFileDialog dlg = new OpenFileDialog();
                dlg.CheckFileExists = true;
                dlg.Filter = "Document Files(*.xaml)|*.xaml|All files (*.*)|*.*";

                if ((bool)dlg.ShowDialog(this))
                {
                    FlowDocument flow = txtbox.Document;
                    TextRange range = new TextRange(flow.ContentStart, flow.ContentEnd);
                    Stream strm = null;
                    try
                    {
                        strm = new FileStream(dlg.FileName, FileMode.Open);
                        range.Load(strm, DataFormats.Xaml);
                    }catch (Exception exc) {
                        MessageBox.Show(exc.Message, Title);
                    }finally{
                        if (strm != null)
                            strm.Close();
                    }
                }
                args.Handled = true;
            }
            base.OnPreviewTextInput(args);
        }
    }








24.39.RichTextBox
24.39.1.Programmatically Insert Text into a RichTextBoxProgrammatically Insert Text into a RichTextBox
24.39.2.Get selected text from RichTextBox by using RichTextBox.Selection.TextGet selected text from RichTextBox by using RichTextBox.Selection.Text
24.39.3.Get Caret Position in a RichTextBox by using RichTextBox.CaretPosition.GetPositionAtOffsetGet Caret Position in a RichTextBox by using RichTextBox.CaretPosition.GetPositionAtOffset
24.39.4.Add / Remove TextChanged event for RichTextBoxAdd / Remove TextChanged event for RichTextBox
24.39.5.Select all text from RichTextBox and cutSelect all text from RichTextBox and cut
24.39.6.Load or Save the Content of a RichTextBoxLoad or Save the Content of a RichTextBox
24.39.7.Get the content from the rich text box.Get the content from the rich text box.
24.39.8.Apply Syntax Highlighting in a Text ControlApply Syntax Highlighting in a Text Control
24.39.9.Edit Rich Text with RichTextBox
24.39.10.Get FlowDocument from RichTextBox