Subscribe to danzar's Blog        RSS Feed
-----

Mega Project ideal list. - "Text" section / Text Editor

Icon Leave Comment
Ok, this one took me a couple of days. I was having an issue on the text color after a highlighted section staying the same color as the last highlight.

I was able to fix it with this line
textboxInput.Selection.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Black);


It saves,loads and opens txt files and loads them into a Richtextbox. Then from a Dic list in the code it will highlight all text that match them.


namespace Text_Editor
{
    /// <summary>
    /// Interaction logic for Mainwindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            textchaned = false;
            InitializeComponent();
            textarea_rtb.SetValue(Paragraph.LineHeightProperty, 5.0);
        }
        private bool textchaned { set; get; }

        private void menuNew_Click(object sender, RoutedEventArgs e)
        {
            if (textchaned)
            { wanttosave(textarea_rtb); }
            textarea_rtb.document.Blocks.Clear();
            textchaned = false;
        }

        private void menuSave_Click(object sender, RoutedEventArgs e)
        {
             wanttosave(textarea_rtb);
        }

        private void menuExit_Click(object sender, RoutedEventArgs e)
        {
            if (textchaned)
            { wanttosave(textarea_rtb); }
            this.Close();
        }
        private void menuOpen_Click(object sender, RoutedEventArgs e)
        {
            StreamReader myStream = null;

            if (textchaned)
            {//ask to save first
                wanttosave(textarea_rtb);
            }

            textarea_rtb.document.Blocks.Clear();

            OpenFileDialog open_file = new OpenFileDialog();
            open_file.DefaultExt = ".txt";
            open_file.Filter = "(.txt)|*.txt";
            bool? okClicked = open_file.ShowDialog();

            if (okClicked == true)
            {
                if ((myStream = new StreamReader(open_file.FileName)) != null)
                {
                    using (myStream)
                    {
                        string text = myStream.ReadToEnd();
                        textarea_rtb.AppendText(text);
                    }

                }
            }      
        }

        private void hightlightwords(RichTextBox textboxInput)
        {
           TextRange myrange;
            
            foreach (var word in highlightwordlist())//loop the list for words
            {
                TextPointer newContentStart = textboxInput.document.ContentStart; //restart back at the top of the richtextbox.
                while ((myrange = FindWordFromPosition(newContentStart, word.Key)) != null)//loop though the text for each case of the word
                {
                    myrange.ApplyPropertyValue(TextElement.ForegroundProperty, word.Value);
                    newContentStart = myrange.End;                   
                }
                
            }
            textboxInput.Selection.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Black); //Set the text back to black after the highlights.
        }

        private static Dictionary<string, Brush> highlightwordlist()
        {
            Dictionary<string, Brush> highlightwords = new Dictionary<string, Brush>();
            highlightwords.Add("<amp>",Brushes.Red);
            highlightwords.Add("</amp>", Brushes.Red);
            highlightwords.Add("<text>", Brushes.Blue);
            highlightwords.Add("</text>", Brushes.Blue);
            highlightwords.Add("<trash>", Brushes.Green);
            return highlightwords;
        }

        /// Got this method(ideal) from http://stackoverflow.com/questions/982916/how-to-find-a-textrange-in-richtextbox-between-two-textpointers
        /// however the ideal come from http://msdn.microsoft.com/en-us/library/system.windows.documents.textpointer.aspx
        /// and all he did was convert it from  returning just the pointer for the word, to returning the range for the word 
        /// by making a second(end pointer) pointer based off the legth of the word. 
        TextRange FindWordFromPosition(TextPointer position, string word)
        {
            while (position != null)
            {
                if (position.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
                {
                    string textRun = position.GetTextInRun(LogicalDirection.Forward);

                    // Find the starting index of any substring that matches "word".
                    int indexInRun = textRun.IndexOf(word);
                    if (indexInRun >= 0)
                    {
                        TextPointer start = position.GetPositionAtOffset(indexInRun);
                        TextPointer end = start.GetPositionAtOffset(word.Length);
                        return new TextRange(start, end);
                    }
                }

                position = position.GetNextContextPosition(LogicalDirection.Forward);
            }

            // position will be null if "word" is not found.
            return null;
        }

        private void wanttosave(RichTextBox rtextbox)
        {
            MessageBoxResult result;
            result = MessageBox.Show("Do you wish to save the current text file?", "Save file", MessageBoxButton.YesNo);
           if (result == MessageBoxResult.Yes) 
           {
               SaveFileDialog savefile = new SaveFileDialog();
               savefile.Filter = "(.txt)|*.txt";
               if (savefile.ShowDialog() == true)
               {
                   TextRange textrange = new TextRange(rtextbox.document.ContentStart, rtextbox.document.ContentEnd);
                   File.WriteAllText(savefile.FileName, textrange.Text);
                   textchaned = false;
               }
           }
        }
       
        private void textarea_rtb_TextChanged(object sender, TextChangedEventArgs e)
        {
            textchaned = true;
            hightlightwords(textarea_rtb);
        }
        
    }
}

Attached File(s)

0 Comments On This Entry

 

Trackbacks for this entry [ Trackback URL ]

There are no Trackbacks for this entry

October 2017

S M T W T F S
1234567
891011121314
15 16 1718192021
22232425262728
293031    

Tags

    Search My Blog

    0 user(s) viewing

    0 Guests
    0 member(s)
    0 anonymous member(s)