Jump to content

c# syntax highlighting


fiveworlds

Recommended Posts

Trying to create a richtextbox with intellisense and syntax highlighting in C# windows form application. Totally confused with the whole thing most examples I look up either no longer work in visual studio, wrong or for C++ etc.

 

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Documents;
using System.Windows.Forms.Design;
using ColorCode;
namespace test
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            LineNumberTextBox.Font = richTextBox1.Font;

            richTextBox1.Select();
            AddLineNumbers();
            string[] words =
            {
                "Example",
                "public",
                "Highlighting",
            };
            Color[] colors =
            {
                Color.Aqua, Color.CadetBlue,
                Color.Orchid
            };
            for (int i = 0; i < words.Length; i++)
            {
                 string word = words[i];
                 Color color = colors[i];
                {
                    richTextBox1.SelectionColor = color;
                    richTextBox1.AppendText(word);
                    richTextBox1.AppendText(" ");
                }
                
            }
            richTextBox1.SelectionColor = Color.Black;
       }

        public int getWidth()
        {
            int w = 25;
            // get total lines of richTextBox1    
            int line = richTextBox1.Lines.Length;
            if (line <= 99)
            {
                w = 20 + (int)richTextBox1.Font.Size;
            }
            else if (line <= 999)
            {
                w = 30 + (int)richTextBox1.Font.Size;
            }
            else
            {
                w = 50 + (int)richTextBox1.Font.Size;
            }
            return w;
        }
        public void AddLineNumbers()
        {
            // create & set Point pt to (0,0)    
            Point pt = new Point(0, 0);
            // get First Index & First Line from richTextBox1    
            int First_Index = richTextBox1.GetCharIndexFromPosition(pt);
            int First_Line = richTextBox1.GetLineFromCharIndex(First_Index);
            // set X & Y coordinates of Point pt to ClientRectangle Width & Height respectively    
            pt.X = ClientRectangle.Width;
            pt.Y = ClientRectangle.Height;
            // get the font Size of richTextBox1 and update LineNumberTextBox
            LineNumberTextBox.Font = new Font(LineNumberTextBox.Font.Name, richTextBox1.Font.SizeInPoints,
                LineNumberTextBox.Font.Style, richTextBox1.Font.Unit);
            // get Last Index & Last Line from richTextBox1    
            int Last_Index = richTextBox1.GetCharIndexFromPosition(pt);
            int Last_Line = richTextBox1.GetLineFromCharIndex(Last_Index);
            // set Center alignment to LineNumberTextBox    
            LineNumberTextBox.SelectionAlignment = HorizontalAlignment.Center;
            // set LineNumberTextBox text to null & width to getWidth() function value    
            LineNumberTextBox.Text = "";
            LineNumberTextBox.Width = getWidth();
            // now add each line number to LineNumberTextBox upto last line    
            for (int i = First_Line; i <= Last_Line+1; i++)
            {
                LineNumberTextBox.Text += i + 1 + "\n";
            }
        }
        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Clear();
        }
        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog op = new OpenFileDialog();
            if (op.ShowDialog() == DialogResult.OK)
                richTextBox1.LoadFile(op.FileName, RichTextBoxStreamType.PlainText);
            this.Text = op.FileName;
        }
        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog sv = new SaveFileDialog();
            sv.Filter = "Text Documents(*.txt)|*.txt|All Files(*.*)|*.*";
            if (sv.ShowDialog() == DialogResult.OK)
                richTextBox1.SaveFile(sv.FileName,RichTextBoxStreamType.PlainText);
            this.Text = sv.FileName;
        }
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
        private void cutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Cut();
        }
        private void copyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Copy();
        }
        private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Paste();
        }
        private void undoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Undo();
        }
        private void redoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Redo();
        }
        private void fontToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            FontDialog fd = new FontDialog();
            fd.Font = richTextBox1.SelectionFont;
            if (fd.ShowDialog() == DialogResult.OK)
            {
                richTextBox1.Font = fd.Font;
                LineNumberTextBox.Font = fd.Font;
            }
        }
        private void backgroundToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ColorDialog cr = new ColorDialog();
            if(cr.ShowDialog() == DialogResult.OK)
            {
                richTextBox1.BackColor = cr.Color;
            }
        }
        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Ver 1.0.0\nCreated by David Mather");
        }

        private void richTextBox1_SelectionChanged(object sender, EventArgs e)
        {
            AddLineNumbers();
        }
        private void richTextBox1_VScroll(object sender, EventArgs e)
        {
            LineNumberTextBox.Text = "";
            AddLineNumbers();
            LineNumberTextBox.Invalidate();
        }

        private void richTextBox1_FontChanged(object sender, EventArgs e)
        {
            LineNumberTextBox.Font = richTextBox1.Font;
            richTextBox1.Select();
            AddLineNumbers();
        }
        private void LineNumberTextBox_MouseDown(object sender, MouseEventArgs e)
        {
            richTextBox1.Select();
            LineNumberTextBox.DeselectAll();
        }
        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {
            AddLineNumbers();
            string[] lines = richTextBox1.Lines;
            lines[0] = lines[0] + "test";
            richTextBox1.Clear();
            richTextBox1.Lines = lines;
            /*
                lines[richTextBox1.GetLineFromCharIndex(cursorPosition)] = "";

                for (int i = 0; i < words.Length-1; i++)
                {
                    int test = 0;
                    foreach(var teststring in dictionary )
                    {
                        if(words[i].Equals(teststring))
                        {
                            test = 1;
                        }
                    }
                    if(test == 1)
                    {
                        richTextBox1.SelectionColor = Color.Red;
                        lines[richTextBox1.GetLineFromCharIndex(cursorPosition)] = lines[richTextBox1.GetLineFromCharIndex(cursorPosition)] + words[i] + " ";
                    }
                    else
                    {
                        richTextBox1.SelectionColor = Color.Black;
                        lines[richTextBox1.GetLineFromCharIndex(cursorPosition)] = lines[richTextBox1.GetLineFromCharIndex(cursorPosition)] + words[i] + " ";
                    }
                }
                richTextBox1.SelectionColor = Color.Red;
                lines[richTextBox1.GetLineFromCharIndex(cursorPosition)] = lines[richTextBox1.GetLineFromCharIndex(cursorPosition)] + words[words.Length-1];
                richTextBox1.Lines = lines;
                */
        }
        private void richTextBox1_Resize(object sender, EventArgs e)
        {
            AddLineNumbers();
        }
    }
}

I am trying to read in the line I am currently typing and highlight the text but I can't seem to get it to work. For instance.

            string[] lines = richTextBox1.Lines;
            lines[0] = lines[0] + "test";
            richTextBox1.Clear();
            richTextBox1.Lines = lines;

I would assume to get only one instance of the word test but instead I have six instances of the word test one after each word in that line and I have absolutely no idea why it is doing that. Looking through stackoverflow I found few references to scintillaNet but visual studio wouldn't open it(no idea why) and colorCode(that didn't work either).

 

 

 

Edited by fiveworlds
Link to comment
Share on other sites

I am trying to read in the line I am currently typing and highlight the text but I can't seem to get it to work. For instance.

If you're editing text, textChanged() method is called,

and there you alter text,

isn't textChanged() method called again, and again?

In infinite loop?

 

I would assume to get only one instance of the word test but instead I have six instances of the word test one after each word in that line and I have absolutely no idea why it is doing that.

The most likely reentering function, in recurrence, like I said above. Surprising you didn't end up in infinite loop (which ends up with stack overflow quite soon). Maybe C# has some recursion counter to avoid this.

 

If you're not sure what happens in the code, put there debug logging some variables with description to console, or to file.

(it's useful when you cannot put debug breakpoint and went there using debugger)

Edited by Sensei
Link to comment
Share on other sites

If you're editing text, textChanged() method is called,

and there you alter text,

isn't textChanged() method called again, and again?

In infinite loop?

 

 

Only when the text is changed in the richtextbox say the word public is set to highlight. When I delete a letter from it then it shouldn't highlight anymore. Similarly if I add a letter to it then it shouldn't highlight anymore.

 

 

If you're not sure what happens in the code, put there debug logging some variables with description to console, or to file.​

 

 

It was working with syntax highlighting and intellisense for richtextbox1.Text but that would only work on the first line of text for some reason. So lines is supposed to read all the lines into an array. However when I try to concatenate "test" to the end of the first line which contains the highlighted words "Example Syntax Highlighting" I get "Example test test Syntax test test Highlighting test test". I suppose if the method was called twice then it would make sense to have 2 tests but not to have 6 tests.

Link to comment
Share on other sites

This is how you should make highlighting in RichTextBox (C++ example):

// Copyright (c) 2016 Sensei
private: System::Void richTextBox1_TextChanged(System::Object^  sender, System::EventArgs^  e) {
                 RichTextBox ^richTextBox1 = this->richTextBox1;

                 System::Collections::ArrayList ^rows = gcnew ArrayList( richTextBox1->Lines );

                 int current = richTextBox1->SelectionStart;

                 richTextBox1->Clear();

                 ArrayList ^dictionary = gcnew ArrayList();
                 dictionary->Add( L"highlight" );
                 dictionary->Add( L"my" );
                 dictionary->Add( L"text" );

                 int row_index = 0;
                 for each( String ^row in rows )
                 {
                     array<String ^> ^words = row->Split( ' ' );
                     int word_index = 0;
                     for each( String ^word in words )
                     {
                        bool selected = dictionary->Contains( word );
                        if( selected != false )
                        {
                            Color old_color = richTextBox1->SelectionColor;
                            richTextBox1->SelectionColor = Color::Red;
                            richTextBox1->SelectedText = word;
                            richTextBox1->SelectionColor = old_color;
                        }
                        else
                        {
                            richTextBox1->AppendText( word );
                        }
                        word_index++;
                        if( word_index < words->Length ) richTextBox1->AppendText( L" " );
                    }
                     row_index++;
                     if( row_index < rows->Count ) richTextBox1->AppendText( L"\n" );
                 }
                 richTextBox1->SelectionStart = current;
             }

Example usage:

post-100882-0-77605500-1479041710.png

 

As you can see it does not use RichTextBox->Lines..

Edited by Sensei
Link to comment
Share on other sites

This is how you should make highlighting in RichTextBox (C++ example):​

 

 

Cool I might rewrite the whole thing for c++ dunno why lines isn't working for me. I could try richtextbox.rtf but that requires a whole rich text parser...

 

edit

 

Finally got it working

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Documents;
using System.Windows.Forms.Design;
using ColorCode;
namespace Vedit
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            LineNumberTextBox.Font = richTextBox1.Font;

            richTextBox1.Select();
            AddLineNumbers();
            string[] words =
            {
                "Example",
                "public",
                "Highlighting",
            };
            Color[] colors =
            {
                Color.Aqua, Color.CadetBlue,
                Color.Orchid
            };
            for (int i = 0; i < words.Length; i++)
            {
                 string word = words[i];
                 Color color = colors[i];
                {
                    richTextBox1.SelectionColor = color;
                    richTextBox1.AppendText(word);
                    richTextBox1.AppendText(" ");
                }
                
            }
            richTextBox1.SelectionColor = Color.Black;
       }

        public int getWidth()
        {
            int w = 25;
            // get total lines of richTextBox1    
            int line = richTextBox1.Lines.Length;
            if (line <= 99)
            {
                w = 20 + (int)richTextBox1.Font.Size;
            }
            else if (line <= 999)
            {
                w = 30 + (int)richTextBox1.Font.Size;
            }
            else
            {
                w = 50 + (int)richTextBox1.Font.Size;
            }
            return w;
        }
        public void AddLineNumbers()
        {
            // create & set Point pt to (0,0)    
            Point pt = new Point(0, 0);
            // get First Index & First Line from richTextBox1    
            int First_Index = richTextBox1.GetCharIndexFromPosition(pt);
            int First_Line = richTextBox1.GetLineFromCharIndex(First_Index);
            // set X & Y coordinates of Point pt to ClientRectangle Width & Height respectively    
            pt.X = ClientRectangle.Width;
            pt.Y = ClientRectangle.Height;
            // get the font Size of richTextBox1 and update LineNumberTextBox
            LineNumberTextBox.Font = new Font(LineNumberTextBox.Font.Name, richTextBox1.Font.SizeInPoints,
                LineNumberTextBox.Font.Style, richTextBox1.Font.Unit);
            // get Last Index & Last Line from richTextBox1    
            int Last_Index = richTextBox1.GetCharIndexFromPosition(pt);
            int Last_Line = richTextBox1.GetLineFromCharIndex(Last_Index);
            // set Center alignment to LineNumberTextBox    
            LineNumberTextBox.SelectionAlignment = HorizontalAlignment.Center;
            // set LineNumberTextBox text to null & width to getWidth() function value    
            LineNumberTextBox.Text = "";
            LineNumberTextBox.Width = getWidth();
            // now add each line number to LineNumberTextBox upto last line    
            for (int i = First_Line; i <= Last_Line+1; i++)
            {
                LineNumberTextBox.Text += i + 1 + "\n";
            }
        }
        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Clear();
        }
        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog op = new OpenFileDialog();
            if (op.ShowDialog() == DialogResult.OK)
                richTextBox1.LoadFile(op.FileName, RichTextBoxStreamType.PlainText);
            this.Text = op.FileName;
        }
        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog sv = new SaveFileDialog();
            sv.Filter = "Text Documents(*.txt)|*.txt|All Files(*.*)|*.*";
            if (sv.ShowDialog() == DialogResult.OK)
                richTextBox1.SaveFile(sv.FileName,RichTextBoxStreamType.PlainText);
            this.Text = sv.FileName;
        }
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
        private void cutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Cut();
        }
        private void copyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Copy();
        }
        private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Paste();
        }
        private void undoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Undo();
        }
        private void redoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Redo();
        }
        private void fontToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            FontDialog fd = new FontDialog();
            fd.Font = richTextBox1.SelectionFont;
            if (fd.ShowDialog() == DialogResult.OK)
            {
                richTextBox1.Font = fd.Font;
                LineNumberTextBox.Font = fd.Font;
            }
        }
        private void backgroundToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ColorDialog cr = new ColorDialog();
            if(cr.ShowDialog() == DialogResult.OK)
            {
                richTextBox1.BackColor = cr.Color;
            }
        }
        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Ver 1.0.0\nCreated by David Mather");
        }

        private void richTextBox1_SelectionChanged(object sender, EventArgs e)
        {
            AddLineNumbers();
        }
        private void richTextBox1_VScroll(object sender, EventArgs e)
        {
            LineNumberTextBox.Text = "";
            AddLineNumbers();
            LineNumberTextBox.Invalidate();
        }

        private void richTextBox1_FontChanged(object sender, EventArgs e)
        {
            LineNumberTextBox.Font = richTextBox1.Font;
            richTextBox1.Select();
            AddLineNumbers();
        }
        private void LineNumberTextBox_MouseDown(object sender, MouseEventArgs e)
        {
            richTextBox1.Select();
            LineNumberTextBox.DeselectAll();
        }
        public void HighlightText(RichTextBox myRtb, string word, Color color)
        {
            if (word == string.Empty)
                return;
            int s_start = myRtb.SelectionStart, startIndex = 0, index;
            while ((index = myRtb.Text.IndexOf(word, startIndex)) != -1)
            {
                myRtb.Select(index, word.Length);
                myRtb.SelectionColor = color;
                startIndex = index + word.Length;
            }
            myRtb.SelectionStart = s_start;
            myRtb.SelectionLength = 0;
            myRtb.SelectionColor = Color.Black;
        }
        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {
            AddLineNumbers();
            HighlightText(richTextBox1, "Example", Color.Red);           
        }
        private void richTextBox1_Resize(object sender, EventArgs e)
        {
            AddLineNumbers();
        }
    }
}
Edited by fiveworlds
Link to comment
Share on other sites

I have now even better version.

It has configurable color for each word,

and comparison case-sensitive or non-case-sensitive.

 

post-100882-0-15441500-1479054679.png

 

DictionaryWord.h

#pragma once

namespace TestRichTextBox {

	using namespace System;
	using namespace System::Drawing;

	ref class DictionaryWord : public Object
	{
	private:
		String ^m_Word;
		Color m_Color;

	public:
		DictionaryWord( String ^word, Color color );

		System::Void SetWord( String ^word );
		String ^GetWord( System::Void );

		System::Void SetColor( Color color );
		Color GetColor( System::Void );
	};
};

DictionaryWord.cpp

#include "StdAfx.h"
#include "DictionaryWord.h"

namespace TestRichTextBox {

	using namespace System;
	using namespace System::Drawing;

	DictionaryWord::DictionaryWord(  String ^word, Color color )
	{
		this->m_Word = word;
		this->m_Color = color;
	}

	System::Void DictionaryWord::SetWord( String ^word )
	{
		this->m_Word = word;
	}

	String ^DictionaryWord::GetWord( System::Void )
	{
		return( this->m_Word );
	}

	System::Void DictionaryWord::SetColor( Color color )
	{
		this->m_Color = color;
	}
	
	Color DictionaryWord::GetColor( System::Void )
	{
		return( this->m_Color );
	}
};

Dictionary.h

#pragma once


namespace TestRichTextBox {

	using namespace System;
	using namespace System::ComponentModel;
	using namespace System::Collections;

ref class DictionaryWord;

ref class Dictionary : public ArrayList
{
public:
	Dictionary(void);

	DictionaryWord ^FindWord( String ^word, System::Boolean ignore_case );
};
};

Dictionary.cpp

#include "StdAfx.h"
#include "Dictionary.h"

namespace TestRichTextBox {

	Dictionary::Dictionary(void)
	{
	}

	DictionaryWord ^Dictionary::FindWord( String ^word, System::Boolean ignore_case )
	{
		for each( DictionaryWord ^dictionary_word in this )
		{
			String ^w = dictionary_word->GetWord();

			int result = String::Compare( w, word, ignore_case );
			if( result == 0 )
			{
				return( dictionary_word );
			}
		}
		return( nullptr );
	}
};

Form1.h

	private: System::Void richTextBox1_TextChanged(System::Object^  sender, System::EventArgs^  e) {

				 RichTextBox ^richTextBox1 = this->richTextBox1;

				 System::Collections::ArrayList ^rows = gcnew ArrayList( richTextBox1->Lines );

				 int current = richTextBox1->SelectionStart;

				 richTextBox1->Clear();

				 Dictionary ^dictionary = gcnew Dictionary();
				 dictionary->Add( gcnew DictionaryWord( L"highlight", Color::Red ) );
				 dictionary->Add( gcnew DictionaryWord( L"my", Color::Green ) );
				 dictionary->Add( gcnew DictionaryWord( L"text", Color::Blue ) );

				 int row_index = 0;
				 for each( String ^row in rows )
				 {
					 array<String ^> ^words = row->Split( ' ' );
					 int word_index = 0;
					 for each( String ^word in words )
					 {
						 DictionaryWord ^dictionary_word = dictionary->FindWord( word, true );
						if( dictionary_word != nullptr )
						{
							Color old_color = richTextBox1->SelectionColor;
							richTextBox1->SelectionColor = dictionary_word->GetColor();
							richTextBox1->SelectedText = word;
							richTextBox1->SelectionColor = old_color;
						}
						else
						{
							richTextBox1->AppendText( word );
						}
						word_index++;
						if( word_index < words->Length ) richTextBox1->AppendText( L" " );
					}
					 row_index++;
					 if( row_index < rows->Count ) richTextBox1->AppendText( L"\n" );
				 }
				 richTextBox1->SelectionStart = current;
			 }

ps. IndexOf() - smart move David. But bye bye to multi-coloring..

 

ps2. Remember SelectionColor at start, and restore it at the end, instead of setting black color.

 

ps3. Obviously dictionary should be sorted, and binary search algorithm used to find word in it, for optimal performance.

Edited by Sensei
Link to comment
Share on other sites

ps. IndexOf() - smart move David. But bye bye to multi-coloring..

 

 

Multi-Coloring is working fine.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Documents;
using System.Windows.Forms.Design;
using ColorCode;
namespace Vedit
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            LineNumberTextBox.Font = richTextBox1.Font;

            richTextBox1.Select();
            AddLineNumbers();
            string[] words =
            {
                "Example",
                "public",
                "Highlighting",
            };
            Color[] colors =
            {
                Color.Aqua, Color.CadetBlue,
                Color.Orchid
            };
            for (int i = 0; i < words.Length; i++)
            {
                 string word = words[i];
                 Color color = colors[i];
                {
                    richTextBox1.SelectionColor = color;
                    richTextBox1.AppendText(word);
                    richTextBox1.AppendText(" ");
                }
                
            }
            richTextBox1.SelectionColor = Color.Black;
       }

        public int getWidth()
        {
            int w = 25;
            // get total lines of richTextBox1    
            int line = richTextBox1.Lines.Length;
            if (line <= 99)
            {
                w = 20 + (int)richTextBox1.Font.Size;
            }
            else if (line <= 999)
            {
                w = 30 + (int)richTextBox1.Font.Size;
            }
            else
            {
                w = 50 + (int)richTextBox1.Font.Size;
            }
            return w;
        }
        public void AddLineNumbers()
        {
            // create & set Point pt to (0,0)    
            Point pt = new Point(0, 0);
            // get First Index & First Line from richTextBox1    
            int First_Index = richTextBox1.GetCharIndexFromPosition(pt);
            int First_Line = richTextBox1.GetLineFromCharIndex(First_Index);
            // set X & Y coordinates of Point pt to ClientRectangle Width & Height respectively    
            pt.X = ClientRectangle.Width;
            pt.Y = ClientRectangle.Height;
            // get the font Size of richTextBox1 and update LineNumberTextBox
            LineNumberTextBox.Font = new Font(LineNumberTextBox.Font.Name, richTextBox1.Font.SizeInPoints,
                LineNumberTextBox.Font.Style, richTextBox1.Font.Unit);
            // get Last Index & Last Line from richTextBox1    
            int Last_Index = richTextBox1.GetCharIndexFromPosition(pt);
            int Last_Line = richTextBox1.GetLineFromCharIndex(Last_Index);
            // set Center alignment to LineNumberTextBox    
            LineNumberTextBox.SelectionAlignment = HorizontalAlignment.Center;
            // set LineNumberTextBox text to null & width to getWidth() function value    
            LineNumberTextBox.Text = "";
            LineNumberTextBox.Width = getWidth();
            // now add each line number to LineNumberTextBox upto last line    
            for (int i = First_Line; i <= Last_Line+1; i++)
            {
                LineNumberTextBox.Text += i + 1 + "\n";
            }
        }
        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Clear();
        }
        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog op = new OpenFileDialog();
            if (op.ShowDialog() == DialogResult.OK)
                richTextBox1.LoadFile(op.FileName, RichTextBoxStreamType.PlainText);
            this.Text = op.FileName;
        }
        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog sv = new SaveFileDialog();
            sv.Filter = "Text Documents(*.txt)|*.txt|All Files(*.*)|*.*";
            if (sv.ShowDialog() == DialogResult.OK)
                richTextBox1.SaveFile(sv.FileName,RichTextBoxStreamType.PlainText);
            this.Text = sv.FileName;
        }
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
        private void cutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Cut();
        }
        private void copyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Copy();
        }
        private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Paste();
        }
        private void undoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Undo();
        }
        private void redoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Redo();
        }
        private void fontToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            FontDialog fd = new FontDialog();
            fd.Font = richTextBox1.SelectionFont;
            if (fd.ShowDialog() == DialogResult.OK)
            {
                richTextBox1.Font = fd.Font;
                LineNumberTextBox.Font = fd.Font;
            }
        }
        private void backgroundToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ColorDialog cr = new ColorDialog();
            if(cr.ShowDialog() == DialogResult.OK)
            {
                richTextBox1.BackColor = cr.Color;
            }
        }
        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Ver 1.0.0\nCreated by David Mather");
        }

        private void richTextBox1_SelectionChanged(object sender, EventArgs e)
        {
            AddLineNumbers();
        }
        private void richTextBox1_VScroll(object sender, EventArgs e)
        {
            LineNumberTextBox.Text = "";
            AddLineNumbers();
            LineNumberTextBox.Invalidate();
        }

        private void richTextBox1_FontChanged(object sender, EventArgs e)
        {
            LineNumberTextBox.Font = richTextBox1.Font;
            richTextBox1.Select();
            AddLineNumbers();
        }
        private void LineNumberTextBox_MouseDown(object sender, MouseEventArgs e)
        {
            richTextBox1.Select();
            LineNumberTextBox.DeselectAll();
        }
        public void HighlightText(RichTextBox myRtb, string[] words, Color[] colors)
        {
            for (var i = 0; i < words.Length; i = i + 1) {
                if (words[i] == string.Empty)
                    return;
                int s_start = myRtb.SelectionStart, startIndex = 0, index;
                while ((index = myRtb.Text.IndexOf(words[i], startIndex)) != -1)
                {
                    int temp = 0;
                    for (var t = 0; t < colors.Length; t = t + 1)
                    {
                        myRtb.Select(index + temp, temp + (words[i].Length / colors.Length));
                        myRtb.SelectionColor = colors[t];
                        temp = temp + (words[i].Length / colors.Length);
                    }
                    startIndex = index + words[i].Length;
                }
                myRtb.SelectionStart = s_start;
                myRtb.SelectionLength = 0;
                myRtb.SelectionColor = Color.Black;
            }
        }
        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {
            AddLineNumbers();
            String[] dictionary = {"Example", "Public"};
            Color[] colors = { Color.Red, Color.Green , Color.Violet};
            HighlightText(richTextBox1, dictionary, colors);
           
        }
        private void richTextBox1_Resize(object sender, EventArgs e)
        {
            AddLineNumbers();
        }
    }
}

Link to comment
Share on other sites

Multi-Coloring is working fine.

But try with really large 100-1000 words dictionary..

 

FindWord() could be easily optimized by binary-search algorithm. IndexOf()-loop takes just one word at a time. 1000 words in dictionary, 1000 loops of IndexOf() through entire RichTextBox->Text.

Edited by Sensei
Link to comment
Share on other sites

But try with really large 100-1000 words dictionary..​

 

 

I know and it should really not be using select which can cause the richtextbox to flash blue. But I would have to be able to read the text in the richtextbox some other way than lines or select. Which really just leaves the .Rtf method.

Link to comment
Share on other sites

Okay I tried your project and it wouldn't build it gave an error message saying it was out of date.

 

I didn't give you project, but a few files from it.

How could they be "out of date"?

Using methods no longer supported rather?

 

But if you want, check attachment.

TestRichTextBox.zip

It was compiled by Visual Studio Express 2008 C++.

If you're using different version of VS, fix things that has been changed.

Normally newer VS was converting projects from older version of VS.

Edited by Sensei
Link to comment
Share on other sites

I am using visual studio 2015 on windows 10 anniversary edition. It forces me to build everything for a minimum of windows 10 so they might have dropped supported for legacy windows builds.

 

I got the following error and build failed until I deleted some of the old stuff. Still complains the project is outdated though.

 

Migration Report - TestRichTextBox

Overview
Project Path Errors Warnings Messages TestRichTextBox TestRichTextBox\TestRichTextBox.vcproj 0 15 2 Solution TestRichTextBox.sln 0 1 2
Solution and projects
TestRichTextBox Message TestRichTextBox\TestRichTextBox.vcproj: VCWebServiceProxyGeneratorTool is no longer supported. The tool has been removed from your project settings. TestRichTextBox\TestRichTextBox.vcproj: Attribute 'CopyLocalDependencies' of 'AssemblyReference' is not supported in this version and has been removed during conversion. TestRichTextBox\TestRichTextBox.vcproj: Attribute 'UseDependenciesInBuild' of 'AssemblyReference' is not supported in this version and has been removed during conversion. TestRichTextBox\TestRichTextBox.vcproj: Attribute 'CopyLocalDependencies' of 'AssemblyReference' is not supported in this version and has been removed during conversion. TestRichTextBox\TestRichTextBox.vcproj: Attribute 'UseDependenciesInBuild' of 'AssemblyReference' is not supported in this version and has been removed during conversion. TestRichTextBox\TestRichTextBox.vcproj: Attribute 'CopyLocalDependencies' of 'AssemblyReference' is not supported in this version and has been removed during conversion. TestRichTextBox\TestRichTextBox.vcproj: Attribute 'UseDependenciesInBuild' of 'AssemblyReference' is not supported in this version and has been removed during conversion. TestRichTextBox\TestRichTextBox.vcproj: Attribute 'CopyLocalDependencies' of 'AssemblyReference' is not supported in this version and has been removed during conversion. TestRichTextBox\TestRichTextBox.vcproj: Attribute 'UseDependenciesInBuild' of 'AssemblyReference' is not supported in this version and has been removed during conversion. TestRichTextBox\TestRichTextBox.vcproj: Attribute 'CopyLocalDependencies' of 'AssemblyReference' is not supported in this version and has been removed during conversion. TestRichTextBox\TestRichTextBox.vcproj: Attribute 'UseDependenciesInBuild' of 'AssemblyReference' is not supported in this version and has been removed during conversion. TestRichTextBox\TestRichTextBox.vcproj: All user macros reported below for configuration 'Debug|Win32' are used before their definition, which can cause undesirable build results; this is not supported in this release. You can resolve this by changing the inclusion order of the consuming property sheets and making sure they come after the property sheets defining the user macros. TestRichTextBox\TestRichTextBox.vcproj: MSB4211: C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Microsoft.Cpp.Common.props (128,5); The property "WindowsTargetPlatformVersion" is being set to a value for the first time, but it was already consumed at "C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Microsoft.Cpp.WindowsSDK.props (29,5)". TestRichTextBox\TestRichTextBox.vcproj: All user macros reported below for configuration 'Release|Win32' are used before their definition, which can cause undesirable build results; this is not supported in this release. You can resolve this by changing the inclusion order of the consuming property sheets and making sure they come after the property sheets defining the user macros. TestRichTextBox\TestRichTextBox.vcproj: MSB4211: C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Microsoft.Cpp.Common.props (128,5); The property "WindowsTargetPlatformVersion" is being set to a value for the first time, but it was already consumed at "C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Microsoft.Cpp.WindowsSDK.props (29,5)". Show 2 additional messages TestRichTextBox\TestRichTextBox.vcproj: Converting project file 'C:\Users\David\Downloads\TestRichTextBox\TestRichTextBox\TestRichTextBox.vcproj'. TestRichTextBox\TestRichTextBox.vcproj: Done converting to new project file 'C:\Users\David\Downloads\TestRichTextBox\TestRichTextBox\TestRichTextBox.vcxproj'. Hide 2 additional messages Solution Message TestRichTextBox.sln: Visual Studio needs to make non-functional changes to this project in order to enable the project to open in Visual Studio 2015, Visual Studio 2013, Visual Studio 2012, and Visual Studio 2010 SP1 without impacting project behavior. Show 2 additional messages TestRichTextBox.sln: File successfully backed up as C:\Users\David\Downloads\TestRichTextBox\Backup\TestRichTextBox.sln TestRichTextBox.sln: Solution migrated successfully Hide 2 additional messages

 

Edited by fiveworlds
Link to comment
Share on other sites

This is report from migration. Just warnings from what I see.

Show what happens while trying to build project.

Screen-shot?

There is no mention at which line there is problem?

 

Did you try opening project properties.

In my version there is such drop-down list,

with .NET Frameworks installed on machine.

And I have there picked up .NET Framework v3.5.

post-100882-0-57567000-1479135586_thumb.png

But Windows 10 has probably v4.5, or v4.6.x

Check what do you have installed, and try to change to more recent.

Edited by Sensei
Link to comment
Share on other sites

Check what do you have installed, and try to change to more recent.​

 

 

I have .net framework v2 - v4.6. The project isn't using the .net framework according to https://msdn.microsoft.com/en-us/library/ff770576.aspx <TargetFrameworkVersion> isn't in the .vcxproj file. It runs it just says it's outdated. Hmm maybe c++ itself changed.

Edited by fiveworlds
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.