Click here to Skip to main content
11,494,851 members (35,869 online)
Click here to Skip to main content

Syntax highlighting textbox written in C#

, 13 Jul 2005 709.4K 8.5K 217
Rate this:
Please Sign up or sign in to vote.
This article describes the code of a RichTextBox that knows how to highlight parts of the text and provide auto-completion.

Sample Image

Introduction

Hey. This code is a class derived from .Net's RichTextBox. It offers syntax highlighting and auto-completion features (like Intellisense, only a little dumber).

Background

Have you ever written an application that had its own script language? Ever needed to edit SQL/code in you application? Didn't you just want a control that was a little better than a TextBox with a fixed width font? Now you can have it Smile | :)

This control was written when I needed to edit SQLs in an application I wrote. Then I thought:

"Even if I could find a control that knows to edit SQLs well, it still wouldn't highlight names of tables or stored procedures that I wrote. And I know I'll need a control that can highlight my own script language sometime..."

So I sat down and wrote it. Later I realized that syntax highlighting without an auto-completion is not worth much, so I added support for that too.

Using the code

First of all, I must apologise. I'm not much of a GUI programmer, so all of the manipulation is done using code, as I lack the knowledge to write custom editors for a PropertyGrid. With that out of the way, we may continue! The control has two inputs for highlighting:

  1. Separators: Accessed using the Seperators property.

    Each separator is a char, and what is later refferd to as "token" is a not-empty string between separators.

  2. Highlight Descriptor: You can use the (how surprising) HighlightDescriptor method to add a HighlightDescriptor.

    A HighlightDescriptor is an instance of a class describing a highlighting rule, which can be divided into token identification info and design info.

Highlighting Rules

A highlighting rule has 6 fields it's constructed with:

  • Token: A string that is later compared to the text.
  • DescriptorType: Sets the highlighting type. The options are in a single word, to the end of the line, and to the corresponding closing token.
  • DescriptorRecognition: Determines how the token is compared to the token from the text. The options are: the text is equal to the token, the text begins with the token, and the text contains the token.
  • Color: Sets the color of the token when highlighted.
  • Font: Sets the font on the token when highlighted. This field is optional.
  • UseForAutoComplete: Determines if the token will be used for auto completion.

Due to laziness, a HighlightDescriptor's values can only be set in the constructor. <SideNote> I really think that the readonly keyword is under appreciated.</SideNote>.

The HighlightDescriptor is as follows:

        public class HighlightDescriptor 
        {
            public HighlightDescriptor(string token, 
                   string closeToken, Color color, Font font, 
                   DescriptorType descriptorType, DescriptorRecognition dr, 
                   bool useForAutoComplete) 
            { 
                Color = color; 
                Font = font; 
                Token = token; 
                DescriptorType = descriptorType; 
                CloseToken = closeToken; 
                DescriptorRecognition = dr; 
                UseForAutoComplete = useForAutoComplete; 
            } 
            
            public readonly Color Color; 
            public readonly Font Font; 
            public readonly string Token; 
            public readonly string CloseToken; 
            public readonly DescriptorType DescriptorType; 
            public readonly DescriptorRecognition DescriptorRecognition; 
            public readonly bool UseForAutoComplete; 
        }

Points of Interest

There were a few interesting things during the writing:

  1. Scrollbars: Since every time the text changes, I actually change it again (as far as the base textbox knows), the scrollbars reset themselves to top and left most positions. To resolve this, I used the EM_GETSCROLLPOS and EM_GETSCROLLPOS Windows messages:
            #region Scrollbar positions functions
            /// <summary>
            /// Sends a win32 message to get the scrollbars' position.
            /// </summary>
            /// <returns>a POINT structre containing horizontal
            ///       and vertical scrollbar position.</returns>
            private unsafe Win32.POINT GetScrollPos()
            {
                Win32.POINT res = new Win32.POINT();
                IntPtr ptr = new IntPtr(&res);
                Win32.SendMessage(Handle, Win32.EM_GETSCROLLPOS, 0, ptr);
                return res;
    
            }
    
            /// <summary>
            /// Sends a win32 message to set scrollbars position.
            /// </summary>
            /// <param name="point">a POINT
            ///        conatining H/Vscrollbar scrollpos.</param>
            private unsafe void SetScrollPos(Win32.POINT point)
            {
                IntPtr ptr = new IntPtr(&point);
                Win32.SendMessage(Handle, Win32.EM_SETSCROLLPOS, 0, ptr);
    
            }
            #endregion
  2. Keyboard strokes: During my work on the auto complete feature, I found out that even if you override the OnKeyDown method and not call the base method, keystrokes of keys containing actual characters are still handled (they arrive using the WM_CHAR message). Due to that I decided to override the WndProc method and filter unwanted keystrokes at that level.
  3. RTF: I didn't really learn RTF for this project. I just took a regular RichTextBox and understood what I have to build for my needs. Hence my resulting RTF is probably not optimal. It probably has language limitations that can be solved fairly easily by manipulating the RTF header.

History

  • 05/29/2005: First release.
  • 04/06/2005: Fixed a few bugs when using the ToCloseToken DescriptorType.
  • 07/13/2005: Fixed a few bugs, added Undo/Redo functionality.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Uri Guy
Web Developer
Israel Israel
Hey.
I've been programming since I first understood english at age 10, starting with QBASIC.
I've been developing production C# applications since .Net's first beta, and I enjoy every second of it, as I enjoy sailing, kitesurfing, and playing guitar.

Comments and Discussions

 
BugFont Pin
MarcinJXXXX17-Apr-15 23:36
memberMarcinJXXXX17-Apr-15 23:36 
QuestionLicense Terms for Use of Code Pin
dbhatt7911-Mar-15 7:10
memberdbhatt7911-Mar-15 7:10 
QuestionLicense Type used Pin
dbhatt7923-Feb-15 9:50
memberdbhatt7923-Feb-15 9:50 
QuestionProblem when it has line more Pin
diemtrang8-May-14 0:47
memberdiemtrang8-May-14 0:47 
QuestionThanks Pin
diemtrang7-May-14 19:08
memberdiemtrang7-May-14 19:08 
BugHighlight Color Don't Match Glitch + Can set font\Highlight Pin
Globin21-Dec-12 7:11
memberGlobin21-Dec-12 7:11 
QuestionLicense Pin
Member 877392130-Mar-12 4:16
memberMember 877392130-Mar-12 4:16 
AnswerMe Too! Pin
Globin21-Dec-12 6:34
memberGlobin21-Dec-12 6:34 
QuestionHighlight between ' and ' Pin
Pedro Mendonça5-Jan-12 7:31
memberPedro Mendonça5-Jan-12 7:31 
AnswerRe: Highlight between ' and ' Pin
lordofm23-Aug-12 0:58
memberlordofm23-Aug-12 0:58 
GeneralRe: Highlight between ' and ' Pin
Globin21-Dec-12 7:19
memberGlobin21-Dec-12 7:19 
QuestionThanks Pin
Ross Canning3-Nov-11 15:23
memberRoss Canning3-Nov-11 15:23 
Questionabout licenses Pin
Member 828710218-Oct-11 3:31
memberMember 828710218-Oct-11 3:31 
QuestionPls help Pin
Member 824009118-Sep-11 4:06
memberMember 824009118-Sep-11 4:06 
AnswerRe: Pls help Pin
wizard.ubit25-Sep-11 5:14
memberwizard.ubit25-Sep-11 5:14 
Questionsloved this problem Length < 0 on SetAutoCompleteItems() Method Error Pin
dubbakakishore5-Aug-11 0:18
memberdubbakakishore5-Aug-11 0:18 
GeneralMy vote of 4 Pin
ymmt7-Jun-11 16:26
memberymmt7-Jun-11 16:26 
GeneralLength < 0 on SetAutoCompleteItems() Method Error Pin
Karl_Mauzoul27-Apr-11 6:13
memberKarl_Mauzoul27-Apr-11 6:13 
QuestionWeb version of this? Pin
Rob Achmann18-Jan-11 9:07
memberRob Achmann18-Jan-11 9:07 
QuestionToCloseToken problem Pin
Rex 12412-Jun-10 8:16
memberRex 12412-Jun-10 8:16 
QuestionComments / Multi-Comments with seperators? Pin
DJB MASTER9-May-10 14:09
memberDJB MASTER9-May-10 14:09 
GeneralHighlight existing Text on Startup Pin
nd12798-Mar-10 4:31
membernd12798-Mar-10 4:31 
GeneralVery good, just what I needed. Pin
YetAnotherMember13-Feb-10 10:32
memberYetAnotherMember13-Feb-10 10:32 
GeneralGreat job Pin
juijuijui19-Jan-10 5:30
memberjuijuijui19-Jan-10 5:30 
QuestionThank YOU ++ having a small problem!? Pin
psymail10-Jan-10 2:41
memberpsymail10-Jan-10 2:41 
AnswerRe: Thank YOU ++ having a small problem!? "\\ Temp. solution //" Pin
psymail10-Jan-10 11:51
memberpsymail10-Jan-10 11:51 
GeneralHelp Pin
leosco16-Dec-09 3:36
memberleosco16-Dec-09 3:36 
AnswerRe: Help Pin
chrisbray9-Jan-10 6:48
memberchrisbray9-Jan-10 6:48 
GeneralRewrite GetScrollPos / SetScrollPos to avoid "unsafe" Pin
FPF1-Dec-09 10:09
memberFPF1-Dec-09 10:09 
GeneralScrollBars Pin
Christian_8816-Oct-09 0:48
memberChristian_8816-Oct-09 0:48 
QuestionLicense? Pin
evanssthomas14-Oct-09 19:49
memberevanssthomas14-Oct-09 19:49 
QuestionProblem with {} brakets Pin
Member 648502511-Oct-09 10:15
memberMember 648502511-Oct-09 10:15 
AnswerRe: Problem with {} brakets Pin
matias20613-Dec-09 11:19
membermatias20613-Dec-09 11:19 
GeneralRe: Problem with {} brakets Pin
Member 64850252-Jan-10 6:44
memberMember 64850252-Jan-10 6:44 
Generalcoloring Pin
ashkan87_23-Sep-09 23:45
memberashkan87_23-Sep-09 23:45 
QuestionRegex? Pin
mager17946-Jul-09 18:40
membermager17946-Jul-09 18:40 
GeneralExcellent Job! Pin
HiDensity5-Jun-09 3:19
memberHiDensity5-Jun-09 3:19 
GeneralWOW Pin
jammmie99916-May-09 22:30
memberjammmie99916-May-09 22:30 
GeneralExcellent Work Pin
MarkBrock14-May-09 18:51
memberMarkBrock14-May-09 18:51 
GeneralSelectionTabs property is auto cleared. Pin
hunyunfly25-Mar-09 18:29
memberhunyunfly25-Mar-09 18:29 
GeneralRe: SelectionTabs property is auto cleared. Pin
jonayro5-Apr-09 2:45
memberjonayro5-Apr-09 2:45 
QuestionExplorer flickering issue Pin
Member 165720721-Jan-09 2:54
memberMember 165720721-Jan-09 2:54 
GeneralRe: Explorer flickering issue Pin
donjefe17-Mar-09 4:09
memberdonjefe17-Mar-09 4:09 
GeneralRe: Explorer flickering issue Pin
donjefe17-Mar-09 4:44
memberdonjefe17-Mar-09 4:44 
GeneralRe: Explorer flickering issue Pin
HossNET17-Jun-10 7:07
memberHossNET17-Jun-10 7:07 
QuestionLicensing question Pin
Andrew Stucky17-Oct-08 6:35
memberAndrew Stucky17-Oct-08 6:35 
AnswerRe: Licensing question Pin
mayeki27-Apr-09 23:07
membermayeki27-Apr-09 23:07 
Generalxml highlighting needed Pin
woutc22-Sep-08 3:17
memberwoutc22-Sep-08 3:17 
GeneralRe: xml highlighting needed Pin
woutc22-Sep-08 22:36
memberwoutc22-Sep-08 22:36 
QuestionCan't set '--' as EOL highlight desc... Pin
im_chc23-Aug-08 7:41
memberim_chc23-Aug-08 7:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150520.1 | Last Updated 14 Jul 2005
Article Copyright 2005 by Uri Guy
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid