Click here to Skip to main content
15,300,084 members
Articles / Mobile Apps
Article
Posted 29 May 2005

Stats

908.7K views
12.1K downloads
224 bookmarked

Syntax highlighting textbox written in C#

Rate me:
Please Sign up or sign in to vote.
4.78/5 (81 votes)
13 Jul 20053 min read
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 :-)

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:

C#
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:
    C#
    #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

 
GeneralRe: string literals Pin
grambowk13-Aug-05 23:12
Membergrambowk13-Aug-05 23:12 
GeneralRe: string literals Pin
DotDue18-Aug-05 2:23
MemberDotDue18-Aug-05 2:23 
GeneralRe: string literals Pin
KenBeckett18-Aug-05 5:32
MemberKenBeckett18-Aug-05 5:32 
GeneralRe: string literals Pin
DotDue18-Aug-05 23:19
MemberDotDue18-Aug-05 23:19 
QuestionRe: string literals Pin
Danielku1527-Aug-06 12:27
MemberDanielku1527-Aug-06 12:27 
GeneralRe: string literals Pin
chabbershaw5-Oct-07 8:20
Memberchabbershaw5-Oct-07 8:20 
GeneralHiglightDescriptor Dependencies Pin
htwo27-Jul-05 1:32
Memberhtwo27-Jul-05 1:32 
GeneralChinese characters BUG Pin
KoaQiu26-Jul-05 21:52
MemberKoaQiu26-Jul-05 21:52 
AnswerRe: Chinese characters BUG Pin
kubasov@orizon-navigation.com11-Oct-05 21:13
Memberkubasov@orizon-navigation.com11-Oct-05 21:13 
GeneralRe: Chinese characters BUG Pin
kimble_wu24-Apr-06 2:56
Memberkimble_wu24-Apr-06 2:56 
AnswerRe: Chinese characters BUG Pin
philm2k@gmail.com16-Oct-06 19:49
Memberphilm2k@gmail.com16-Oct-06 19:49 
QuestionCan you make the tab key work Pin
QuantumQuinn22-Jul-05 17:38
MemberQuantumQuinn22-Jul-05 17:38 
AnswerRe: Can you make the tab key work Pin
Uri Guy23-Jul-05 4:02
MemberUri Guy23-Jul-05 4:02 
GeneralRe: Can you make the tab key work Pin
htwo27-Jul-05 1:27
Memberhtwo27-Jul-05 1:27 
GeneralRe: Can you make the tab key work Pin
QuantumQuinn7-Mar-06 6:09
MemberQuantumQuinn7-Mar-06 6:09 
GeneralRe: Can you make the tab key work Pin
Armano10-Apr-06 2:18
MemberArmano10-Apr-06 2:18 
GeneralRe: Can you make the tab key work Pin
Samuel8426-Jul-06 17:23
MemberSamuel8426-Jul-06 17:23 
GeneralRe: Can you make the tab key work Pin
Samuel8426-Jul-06 17:25
MemberSamuel8426-Jul-06 17:25 
Questionsuggestion: syntax file? Pin
Huisheng Chen22-Jul-05 0:07
MemberHuisheng Chen22-Jul-05 0:07 
AnswerRe: suggestion: syntax file? Pin
larma22-Jul-05 0:27
Memberlarma22-Jul-05 0:27 
GeneralRe: suggestion: syntax file? Pin
Iluha[ua]9-Nov-05 3:54
MemberIluha[ua]9-Nov-05 3:54 
GeneralScintilla Pin
stax7619-Jul-05 22:08
Memberstax7619-Jul-05 22:08 
GeneralRe: Scintilla Pin
larma22-Jul-05 1:47
Memberlarma22-Jul-05 1:47 
GeneralRe: Scintilla Pin
stax7622-Jul-05 1:55
Memberstax7622-Jul-05 1:55 
GeneralRe: Scintilla Pin
Kastellanos Nikos12-Dec-05 2:11
MemberKastellanos Nikos12-Dec-05 2:11 

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

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