Click here to Skip to main content
Licence CPOL
First Posted 1 Feb 2012
Views 5,237
Downloads 411
Bookmarked 13 times

Improved RichTextBox - IRTB

By | 21 Feb 2012 | Article
This article describes a simple way to implement Line Numbering, HighLight Line and show current Line and Column
IRTB.png

Introduction

This article presents what I call an Improved RichTextBox control. Why improved? Well, browsing internet you can find a lot of comments pointing out to the different feautures that are missing on the control provided by Microsoft but three of the most obvious are:

  • Line Numbering
  • Highlight the line
  • Show current line and column

The first one has been addressed in several articles like the following ones:

Of course you can find more articles and code snippets related to the line numbering, but while this issue has been solved the highlight line and showing current line/column were still a pending issue. For everyone using Notepad++ or PSPad it is obvious that one of the nice features is to highlight the line where currently the caret is and of course having an indication of line/column can be very helpful.

So what to expect from this article? I will go through these 3 points showing how I solved them for my own project. Please notice that I am new to the .Net world so if anything can be improved or made in a different way please let me know. I hope the information here will be useful for anyone seeking for a small and simple solution for his/her own projects.

The code is divided in the following "Regions":

  • Region "ImprovedRTB Properties"
  • Region "General Subroutines"
  • Region "IRTB Events"
  • Region "Extra Features"

Implementation

The control is formed by two components, a Richtextbox and a PictureBox. The PictureBox will be used to draw the line numbers and the richtextbox will provide all the features we need from a text editor.

IRTB features are:

  • Line Numbering. This can be enabled/disabled at run-time
  • HighLight Line. This can be enabled/disabled at run-time
  • Event Line Number wich provides the information about the Current Line and Column
  • HighLight Line Color can be changed at run-time
  • Prefix for Line Numbering can be enabled/disabled at runtime.
  • Font can be changed at runtime.
  • Zoom
  • Drag/Drop is enabled

Known Issues:

  • Performance is not good with files bigger than 1500Kb and it is really bad with files bigger than 2500Kb when both options, line numbering and highlight, are enabled. This is mainly due the calculations needed to add the numbers and draw the highlight line in top of the RichTextBox
  • Some flickering can be noticed depending of the action or the size of the file.
  • If wrap is set to true it won't give the correct line numbering.

Line Numbering

So let's start with the first point, Line Numbering. You can find several solutions, as I have said before, some of them show really nice graphics but unfortunately this make the control unusable for large files, other ones are just not totally finished and other ones preferred the unmanaged code (sendmessage) approach which is totally valid (I have used it for some other projects), having this in mind I decide to get something in the middle, not too fancy that makes the control unusable and try not to use the "sendmessage" option; so since I have started already with a similar approach to the one proposed by Michael Elly I decided to continue on that line, the key of Michael's code is the way it is calculated the line height. Why? Because as everyone knows the RichTextBox scrolls using smooth scroll so instead of lines it uses pixels, this is due the nature of the control because it can support different formats, fonts, colors, etc. Therefore the only way to scroll is based on pixels rather than lines. So here is the core of the line numbering.

        Dim font_height As Single = IRTBTextContainer.GetPositionFromCharIndex(IRTBTextContainer.GetFirstCharIndexFromLine(2)).Y - IRTBTextContainer.GetPositionFromCharIndex(IRTBTextContainer.GetFirstCharIndexFromLine(1)).Y
        If font_height <= 0 Then font_height = IRTBTextContainer.Font.Height + 1 'Exit Sub
        'Get the first line index and location
        Dim firstIndex As Integer = IRTBTextContainer.GetCharIndexFromPosition(New Point(0, g.VisibleClipBounds.Y + font_height / 3))
        Dim firstLine As Integer = IRTBTextContainer.GetLineFromCharIndex(firstIndex)
        Dim firstLineY As Integer = IRTBTextContainer.GetPositionFromCharIndex(firstIndex).Y

In this way the real height of the line will be calculated giving the exact value needed to paint the numbers on the PictureBox. So now using this value We can calculate the Y position:

                    Dim y As Single
            Do While y < g.VisibleClipBounds.Y + g.VisibleClipBounds.Height
                If i > (IRTBLineCount) Or (i > (IRTBLineNumber + 1) And (IRTBLineNumber + 1) = IRTBLineCount) Then Exit Do '**This line will avoid to paint all possible numbers in the VisibleClipBounds even if the line number on the Richtextbox is 0
                y = firstLineY + 2 + font_height * (i - firstLine - 1) '
                LineNumberingString = Format(i, PrefixFormat) '** To Add some format to the line numbering
                Select Case PBAlign
                    Case IRTBAlignPos.Left
                        PBAlignNumbers = 0
                    Case IRTBAlignPos.Right
                        PBAlignNumbers = CInt(PBNumbering.Width - g.MeasureString(LineNumberingString, IRTBTextContainer.Font).Width * IRTBTextContainer.ZoomFactor)
                End Select
                If i > 0 Then '**To avoid painting the number 0 so in case we are zooming it won’t be shown
                    g.DrawString(LineNumberingString, PLNumberingFont, IRTBBrushes, PBAlignNumbers, y)
                End If
                i += 1
            Loop
            Me.TableLayoutPanel1.ColumnStyles.Item(0).Width = CSng(Math.Ceiling(IRTBTextContainer.Font.Size) * 2) + CInt(g.MeasureString(LineNumberingString, IRTBTextContainer.Font).Width * IRTBTextContainer.ZoomFactor)

Ok, now We have the routine to draw the numbers, great! (Thanks to Michael Elly), but How to use it? When should We call it? Now is when We need to check the event Paint for the PictureBox. How can We trigger this event? And, under What conditions should We do it? The following events must be used for this:

  • Me.SizeChanged
  • IRTBTextContainer.VScroll
  • IRTBTextContainer.MouseWheel
  • IRTBTextContainer.SelectionChanged
  • LoadFileAndNumbering

When any of these events is raised the following sentence should be used:

PBNumbering.Invalidate()

By doing this We are forcing the PictureBox to re-paint so the event Paint will be fired and DrawIRTBLineNumbers will be called.

Here is the code used to do this:

 
       Private Sub PLNumbering_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles PBNumbering.Paint
        If EnableNumbering = True Then
            DrawIRTBLineNumbers(e.Graphics)
            If IRTBForceONPaint = True Then
                OnPaint(Nothing)
                IRTBForceONPaint = False
            End If
        End If
    End Sub

And now numbers will be painted based on the lines shown on the VisibleClipBounds of the RichTextBox.

Highlight Line

Ok, now that We have the numbers painted We can try to get a rectangle highlighting the current line, to do this We need to use the standard Windows GDI+ library (System.Drawing) and We need to override the OnPaint subroutine. It might be that you noticed that there is no Paint event exposed for the RichTextbox control so the only way to get some control on what We want to paint is using the OnPaint method provided by Control. We override the method and We add the needed code to paint the rectangle using the Richtextbox width and the line height based on the Font used.

Why We are not using WndProc to catch the paint event of the RichTextBox? Well I decided to go for the simpler solution but for those ones interested on this approach, here is a link showing how to catch the WM_PAINT message:

So going back to the code that will paint the rectangle:

    Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs)
        Dim RTBPoint As Point
        IRTBTextContainer.Refresh()
        RTBPoint = IRTBTextContainer.GetPositionFromCharIndex(IRTBTextContainer.GetFirstCharIndexOfCurrentLine)
        IRTBDrawRectangle(My.Settings.HighLightColor, 1, RTBPoint.Y, IRTBTextContainer.Width - 1, CInt(IRTBTextContainer.Font.GetHeight))
        IRTBTextContainer.Focus()
    End Sub

First We need to refresh the RichTextBox to clean any draw done before:

     IRTBTextContainer.Refresh()

Then We need to get the Y position of the first character of the current line:

      RTBPoint = IRTBTextContainer.GetPositionFromCharIndex(IRTBTextContainer.GetFirstCharIndexOfCurrentLine)

And finally We can draw the rectangle:

     IRTBDrawRectangle(My.Settings.HighLightColor, 1, RTBPoint.Y, IRTBTextContainer.Width - 1, IRTBTextContainer.Font.GetHeight, True)

Here is the subroutine that will paint the rectangle:

    Private Sub IRTBDrawRectangle(ByVal RTBDrawColor As Color, ByVal RTBPointX As Integer, ByVal RTBPointY As Integer, ByVal RTBWidth As Integer, ByVal RTBHeight As Integer)
        If EnableHighLight = True Then
            Dim MyPen As New System.Drawing.Pen(RTBDrawColor)
            Dim FormGraphics As System.Drawing.Graphics
            Dim MySolidBrush As SolidBrush
            RTBHeight = RTBHeight * IRTBTextContainer.ZoomFactor + 2
            If RTBDrawColor.A > 64 Then
                MySolidBrush = New SolidBrush(Color.FromArgb(64, RTBDrawColor.R, RTBDrawColor.G, RTBDrawColor.B))
            Else
                MySolidBrush = New SolidBrush(RTBDrawColor)
            End If
            FormGraphics = IRTBTextContainer.CreateGraphics()
            FormGraphics.DrawRectangle(MyPen, RTBPointX, RTBPointY, RTBWidth, RTBHeight)
            FormGraphics.FillRectangle(MySolidBrush, RTBPointX, RTBPointY, RTBWidth, RTBHeight)
            MyPen.Dispose()
            FormGraphics.Dispose()
        End If
    End Sub

The result will look like this:

IRTB Example

Figure 1. HighLight Line

Great! Now We have a rectangle painted on top of the RichTextBox and semitransparent, so We can see what it is behind! But now there are some new scenarios to be verified like these ones:

  • What happen if the user types a new letter in the RichTextBox
  • What happen if the user press the arrows
  • What happen if the user decides to zoom (Scroll+Ctrl)
  • What happen if the user press Page Up/Down
  • What happen if the user press Back/Delete/Enter

All these actions will trigger the hidden Paint event for the RichTextBox making the control to redraw and deleting the rectangle highlighting the line. To handle this We need to use some of the events We have used to paint the numbers:

  • Me.SizeChanged
  • IRTBTextContainer.MouseWheel
  • IRTBTextContainer.SelectionChanged

And We need to use few more:

  • IRTBTextContainer.MouseClick
  • IRTBTextContainer.HScroll
  • IRTBTextContainer.GotFocus
  • IRTBTextContainer.KeyDown
  • IRTBTextContainer.KeyUp

Now depending on the conditions We need to call the OnPaint method, by doing this the rectangle will be drawn after the Paint event for the RichTextBox has done its work.

     OnPaint(Nothing)

Since We are looking to highlight the line where the caret is currently positioned, the main event We have to check is SelectionChanged. This event will be fired every time the selection changes inside the RichTextBox so here We can decide what to do based on the actions performed bu the user (Key stroke, Mouse actions, etc)

For that We declare an Enumeration where We define these values:

    Enum IRTBSelectionCase As Integer
        KeysPageUpDown = 1
        KeysLeftRight = 2
        KeysSpecial = 3
        KeysNormal = 4
        Mouse = 5
    End Enum

We assign these values when the KeyDown/KeyUp events are fired:

    Private Sub RTBTextContainer_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles IRTBTextContainer.KeyDown
        Dim RTBText As RichTextBox
        RTBText = Nothing
        RTBText = sender
        '***Here you can implement different actions for different combination of keys
        Select Case e.KeyCode
            Case Keys.Up
                IRTBKeysSelect = IRTBSelectionCase.KeysPageUpDown
            Case Keys.Down
                IRTBKeysSelect = IRTBSelectionCase.KeysPageUpDown
            Case Keys.Left
                IRTBKeysSelect = IRTBSelectionCase.KeysLeftRight
            Case Keys.Right
                IRTBKeysSelect = IRTBSelectionCase.KeysLeftRight
            Case Keys.Next 'handles Keys.PageDown
                IRTBKeysSelect = IRTBSelectionCase.KeysPageUpDown
            Case Keys.PageUp
                IRTBKeysSelect = IRTBSelectionCase.KeysPageUpDown
            Case Keys.PageDown 'Handles in case of Windows Vista
                IRTBKeysSelect = IRTBSelectionCase.KeysPageUpDown
            Case Keys.Enter
                IRTBKeysSelect = IRTBSelectionCase.KeysSpecial
            Case Keys.Back
                IRTBKeysSelect = IRTBSelectionCase.KeysSpecial
            Case Keys.Delete
                IRTBKeysSelect = IRTBSelectionCase.KeysSpecial
                RTBGetLineCol()
                IRTBTextContainer_SelectionChanged(Nothing, Nothing)
            Case e.Control = True And Keys.V '*******Here is how to catch CTRL+KEYS
                IRTBKeysSelect = IRTBSelectionCase.KeysSpecial
            Case e.Control And Keys.Home
                IRTBKeysSelect = IRTBSelectionCase.KeysSpecial
            Case e.Control And Keys.End
                IRTBKeysSelect = IRTBSelectionCase.KeysSpecial
            Case Keys.ControlKey
                IRTBKeysSelect = IRTBSelectionCase.KeysSpecial
            Case Keys.Escape  '********To set the ZOOM to 1 again
                If RTBText.ZoomFactor > 1 Or RTBText.ZoomFactor < 1 Then
                    RTBText.ZoomFactor = 1
                    PBNumbering.Invalidate()
                    Dim IRTBTimer As New Timer
                    IRTBTimer.Interval = 100
                    AddHandler IRTBTimer.Tick, AddressOf TimerPaint
                    IRTBTimer.Start()
                End If
            Case Else
                IRTBKeysSelect = IRTBSelectionCase.KeysNormal
        End Select
    End Sub

But there is a special case the "Delete" key, for this key We need to catch both events, KeyUp and KeyDown. Why? Because if We don't do this the line numbers won't be updated until the key is released, or they will be updated late so there will be numbers for lines that does not exist any more.

    Private Sub IRTBTextContainer_KeyUp(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles IRTBTextContainer.KeyUp
        '***Here you can implement different actions for different combination of keys
        Select Case e.KeyCode
            Case Keys.Delete
                IRTBKeysSelect = IRTBSelectionCase.KeysSpecial
                RTBGetLineCol()
                IRTBTextContainer_SelectionChanged(Nothing, Nothing)
        End Select
    End Sub

So far We have been able to catch all key strokes We need, now We can check what should be done when the SelectionChanged event is fired:

    Private Sub IRTBTextContainer_SelectionChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles IRTBTextContainer.SelectionChanged
        Dim IRTBCurrentLine As Integer
        IRTBLineCount = IRTBTextContainer.Lines.Length
        If IRTBTextContainer.Lines.Count = 0 Then
            IRTBLineCount = 1
        End If
        Select Case IRTBKeysSelect
            Case IRTBSelectionCase.KeysPageUpDown
                RTBGetLineCol()
                IRTBForceONPaint = True
                PBNumbering.Invalidate()
            Case IRTBSelectionCase.KeysLeftRight
                IRTBCurrentLine = IRTBLineNumber
                RTBGetLineCol()
                If IRTBLineNumber <> IRTBCurrentLine Then
                    IRTBForceONPaint = True
                End If
                PBNumbering.Invalidate()
            Case IRTBSelectionCase.KeysSpecial
                RTBGetLineCol()
                IRTBForceONPaint = True
                PBNumbering.Invalidate()
            Case IRTBSelectionCase.KeysNormal
                RTBGetLineCol()
            Case IRTBSelectionCase.Mouse
                RTBGetLineCol()
                PBNumbering.Invalidate()
        End Select
    End Sub

As you can see there are some conditions, please let me go through and explain one by one:

IRTBSelectionCase.KeysNormal

When this option is selected it means the user is typing normal characters so the only action needed is to get the Line and Column position.

RTBSelectionCase.KeysPageUpDown or IRTBSelectionCase.KeysSpecial

In this case the keys pressed could be BACK,ENTER, DELETE, PgDOWN, PgUP, so the Line/Column and the highligh line must be updated.

RTBSelectionCase.KeysLeftRight

When this option is selected is because the user hit the Left or Right arrows so this part of the code guarantee that the correct line is highlighted and it will update the Line/Col information:

       
            Case IRTBSelectionCase.KeysLeftRight
                IRTBCurrentLine = IRTBLineNumber
                RTBGetLineCol()
                If IRTBLineNumber <> IRTBCurrentLine Then
                    IRTBForceONPaint = True
                End If
                PBNumbering.Invalidate()

The subroutine that helps to do this is called RTBGetLineCol, this one is used to get the current Line and Column, but I will go through this later since it is the third point I will show on this article.

Note: Please noticed that there is one scenario where the numbers and the line/col information won't be updated correctly. When the Arrows(Up/Down) are held down the action will be performed but due the calculations needed to paint the numbers and the highlight line depending on the size of the file (more than 350KB) the information will be updated only after the key is released. Unfortunately I have not been able to solve this issue so far.

Correction: Now numbers and highlight line are being updated while the arrows(Up/Down) are being held down. To do this I have changed the following instruction:

PBNumbering.Invalidate()  

For this one:

PBNumbering.Refresh()  

By now We have managed to draw the rectangle based on key strokes, mouse click, but what would happen if We scroll and the caret goes beyond the visible bounds? How can We detect when it is inside the visible bounds again? The following lines of code will do the trick:

        If EnableHighLight = True Then
            '**Here it will redraw the highlight line when the caret position is coming inside the VisibleClipBounds
            Dim CaretPos As Point = IRTBTextContainer.GetPositionFromCharIndex(IRTBTextContainer.GetFirstCharIndexOfCurrentLine)
            If (CaretPos.Y > -10 And CaretPos.Y < 20) Or (CaretPos.Y < IRTBTextContainer.Height + 30 And CaretPos.Y > IRTBTextContainer.Height - 100) Then
                OnPaint(Nothing)
            End If
        End If

This code is part of the subroutine that handles the RichTextBox event VScroll and it will be used only if highlight line is enabled

Line and Column Information

Now that We have Line Numbering and Highlight working the last point is to get the current line and column, these values are calculated on this subroutine:

    Private Sub RTBGetLineCol()
        Dim GetFirstCharIndex As Integer = IRTBTextContainer.GetFirstCharIndexOfCurrentLine
        Dim GetRTBLine = IRTBTextContainer.GetLineFromCharIndex(GetFirstCharIndex)
        Dim GetPosition As Integer = IRTBTextContainer.SelectionStart - GetFirstCharIndex
        If GetPosition < 0 Then GetPosition = 0
        If GetRTBLine >= IRTBTextContainer.Lines.Count Then GetRTBLine = IRTBTextContainer.Lines.Count - 1
        If GetRTBLine = -1 Then GetRTBLine = 0
        IRTBLineNumber = GetRTBLine
        IRTBColumnNumber = GetPosition
        RaiseEvent LineInformation(GetRTBLine + 1 & "," & GetPosition + 1)
    End Sub

After the calculations to get the line and column are done We need to "publish" them so We raise an event that has been declared.

    Public Event LineInformation(ByVal LineStatus As String)

So that is what the last line on this subroutine does, it provides with the needed information to show the line and column.

        RaiseEvent LineInformation(GetRTBLine + 1 & "," & GetPosition + 1)

Here is how it looks when the information provided by this event is used on the example attached:

IRTB Example

Figure 2. Line and Column Information.

And here is the code used on IRTB Test Form to get the information:

    Private Sub ImprovedRTB1_LineInformation(ByVal LineStatus As System.String) Handles Irtb1.LineInformation
        Dim LineInfo As Array
        LineInfo = Split(LineStatus, ",")
        LineColInformation.Text = "Line:" & LineInfo(0) & " Col:" & LineInfo(1)
        TextBox7.Text = LineStatus
    End Sub

Extras

Drag and Drop

As part of the project I decided to add one more feature, Drag and Drop files. So the code to do this is under the region called "Extras" and it is quite simple:

#Region "Extra Features" 'Drop Files
    Private Sub IRTBDragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles IRTBTextContainer.DragDrop
        Dim myFiles() As String
        myFiles = e.Data.GetData(DataFormats.FileDrop)
        For Each mc_file In myFiles
            Dim FileName As String = mc_file.ToString
            LoadFileAndNumbering(FileName)
            RaiseEvent DragDropFileInformation(FileName)
        Next
    End Sub
    Private Sub IRTBDragEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles IRTBTextContainer.DragEnter
        If e.Data.GetDataPresent(DataFormats.FileDrop) Then
            e.Effect = DragDropEffects.All
        End If
    End Sub
#End Region

As you can notice there is an event called DragDropFileInformation. By using this event on the windows form We can get the name of the file, so here is the code used for that:

    Private Sub DragDropnInformation(ByVal FileName As System.String) Handles Irtb1.DragDropFileInformation
        If System.IO.File.Exists(FileName) Then
            Irtb1.FileToLoad = FileName
            Dim finfo As New FileInfo(FileName)
            TextBox10.Text = finfo.Name
            TextBox6.Text = Str(Math.Round(finfo.Length / 1024)) & "Kb"
            TextBox9.Text = Irtb1.IRTBContainer.Lines.Count.ToString
            TextBox8.Text = Str(Irtb1.ShowTotalChar)
        End If
    End Sub

But remember, to be able to use Drag/Drop on a control you need to set this property IRTBTextContainer.AllowDrop to TRUE. This is already done when the control is loaded.

Zoom

One more thing that needs some explanation is how to handle the zoom option when Line Numbering and HighLight Line are enabled. As all we know a common shortcut for the zoom option on the RichTextBox is CTRL+SCROLL. But how to handle this?, how the highlight line and the line numbering will be affected?

First we need to detect the scroll action and the Ctrl Key. Here is the code to detect the Mouse Wheel:

    
    Private Sub IRTBCheckScoll(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles IRTBTextContainer.MouseWheel
        If IRTBKeysSelect = IRTBSelectionCase.KeysSpecial Then
            IRTBForceONPaint = True
        End If
    End Sub
    

And we need to detect if CTRL has been pressed.

    
                Case Keys.ControlKey
                IRTBKeysSelect = IRTBSelectionCase.KeysSpecial
                If IRTBForceONPaint = True Then
                    IRTBKeysSelect = IRTBSelectionCase.KeysSpecial
                    RTBGetLineCol()
                    PBNumbering.Invalidate()
                    OnPaint(Nothing)
                    IRTBForceONPaint = False
                End If
            Case Keys.Escape
                '********To set the ZOOM to 1 again
                If RTBText.ZoomFactor > 1 Or RTBText.ZoomFactor < 1 Then
                    RTBText.ZoomFactor = 1
                    PBNumbering.Invalidate()
                    RTBGetLineCol()
                    OnPaint(Nothing)
                End If
                

There are two keys detected here, CTRL and Escape, when CTRL is detected the IRTBKeysSelect is set to IRTBSelectionCase.KeysSpecial and when the wheel action is fired the IRTBForceONPaint is set to true, by doing this We are sure that while zooming the numbers and the highlight line are refreshed.

When Escape is pressed the zoom will be set to 1 and the line numbers and highlight line will be painted again.

Conclusion

The 3 points mentioned at the beginning of the article have been presented and I hope the information is good enough to give you some ideas. Unfortunately, and you will noticed this, the performance of the RichTextBox is being impacted when Line Numbering and/or High Light Line is enabled. Why is happening this? The principal reason lies in the use of these lines of code:

      Dim CaretPos As Point = IRTBTextContainer.GetPositionFromCharIndex(IRTBTextContainer.GetFirstCharIndexOfCurrentLine)
                                            ...
                                            ...
      Dim firstIndex As Integer = IRTBTextContainer.GetCharIndexFromPosition(New Point(0, g.VisibleClipBounds.Y + font_height / 3))
      Dim firstLine As Integer = IRTBTextContainer.GetLineFromCharIndex(firstIndex)
      Dim firstLineY As Integer = IRTBTextContainer.GetPositionFromCharIndex(firstIndex).Y                                                

These calculations are really CPU intensive when the size of the file increases, therefore the performance of the control is affected by this. As I have read in other articles, and I do agree, if you need a high performance control you have two options, built your own control from scratch or try scintilla

Regarding the actions where the numbers and the highlight line need to be painted again handling the keys is not always easy but all combinations can be detected so we can select what actions should be performed.

Now let's take a look on How to use the control

Using the Control

There are 2 zip files on this article:

  • IRTB_Code.zip
  • IRTB_Demo.zip

To check what can be done with the IRTB control, download IRTB_Demo.zip, unzipped any place you want and then double click on IRTB_Test.exe

The IRTB_Code.zip contains the solution, unzip the file and open the solution. I have added two projects so when the file is open you can see the following:

IRTB Example

Figure 3. Solution Opened on Visual Studio

The one called IRTB is the control and the one called IRTB_Test is a windows form to check the basic functionality of the control.

The properties exposed by the IRTB control are:

  • IRTBFileToLoad
  • IRTBFont
  • IRTBLNFontColor
  • IRTBHighLightColor
  • ShowTotalChar
  • IRTBEnableNumbering
  • IRTBEnableHighLight
  • RTBContainer
  • RTBnumbering
  • IRTBPrefix
  • IRTBAlignNumbers

IRTB Example

Figure 4. IRTB Properties

The purpose adding the windows form was to show what can be done with the control, please check the code and I hope is clear enough and shows what can be done with the IRTB control.

If you are going to use the IRTB control on your personal project don't forget to add the dll on the reference tab, otherwise you will no be able to use it.

IRTB Example

Figure 5. Add IRTB to the Reference tab

Here is the code used on the IRTB_Test windows form:

Imports System.IO
Public Class Form1
    Private Sub ImprovedRTB1_LineInformation(ByVal LineStatus As System.String) Handles Irtb1.LineInformation
        Dim LineInfo As Array
        LineInfo = Split(LineStatus, ",")
        LineColInformation.Text = "Line:" & LineInfo(0) & " Col:" & LineInfo(1)
        TextBox7.Text = LineStatus
    End Sub
    Private Sub DragDropnInformation(ByVal FileName As System.String) Handles Irtb1.DragDropFileInformation
        If System.IO.File.Exists(FileName) Then
            Irtb1.FileToLoad = FileName
            Dim finfo As New FileInfo(FileName)
            TextBox10.Text = finfo.Name
            TextBox6.Text = Str(Math.Round(finfo.Length / 1024)) & "Kb"
            TextBox9.Text = Irtb1.IRTBContainer.Lines.Count.ToString
            TextBox8.Text = Str(Irtb1.ShowTotalChar)
        End If
    End Sub
    Private Sub IRTBCheckLN_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles IRTBCheckLN.CheckedChanged
        Irtb1.EnableNumbering = IRTBCheckLN.Checked
    End Sub

    Private Sub IRTBCheckHL_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles IRTBCheckHL.CheckedChanged
        Irtb1.EnableHighLight = IRTBCheckHL.Checked
    End Sub

    Private Sub IRTBFont_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles IRTBFont.Click
        FontDialog1.ShowDialog()
        Irtb1.IRTBFont = FontDialog1.Font
    End Sub

    Private Sub IRTBHLColor_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles IRTBHLColor.Click
        SelectColor.Color = Irtb1.HighLightColor
        SelectColor.ShowDialog()
        Irtb1.HighLightColor = SelectColor.Color
    End Sub

    Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
        TestLoadFile.ShowDialog()
        If System.IO.File.Exists(TestLoadFile.FileName) Then
            Irtb1.FileToLoad = TestLoadFile.FileName
            Dim finfo As New FileInfo(TestLoadFile.FileName)
            TextBox10.Text = finfo.Name
            TextBox6.Text = Str(Math.Round(finfo.Length / 1024)) & "Kb"
            TextBox9.Text = Irtb1.RTBContainer.Lines.Count.ToString
            TextBox8.Text = Str(Irtb1.ShowTotalChar)
        End If
    End Sub

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        IRTBCheckLN.Checked = Irtb1.EnableNumbering
        IRTBCheckHL.Checked = Irtb1.EnableHighLight
        Irtb1.IRTBPrefix = False
        Irtb1.AlignNumbers = IRTB.IRTB.IRTBAlignPos.Left
        RadioButton1.Checked = True
    End Sub

    Private Sub RadioButton1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadioButton1.CheckedChanged
        Irtb1.AlignNumbers = IRTB.IRTB.IRTBAlignPos.Left
    End Sub

    Private Sub RadioButton2_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadioButton2.CheckedChanged
        Irtb1.AlignNumbers = IRTB.IRTB.IRTBAlignPos.Right
    End Sub

    Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged
        Irtb1.IRTBPrefix = CheckBox1.Checked
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        SelectColor.Color = Irtb1.IRTBLNFontColor
        SelectColor.ShowDialog()
        Irtb1.IRTBLNFontColor = SelectColor.Color
    End Sub
End Class

Please review the project, check the code and if you have any questions let me know. I will try to answer them in the best possible way.

History

February 1st 2012

February 21st 2012

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Juan R. Huertas



Sweden Sweden

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralMy vote of 5 Pinmembermanoj kumar choubey19:34 19 Mar '12  
GeneralRe: My vote of 5 PinmemberJuan R. Huertas21:49 19 Mar '12  
QuestionGood job! PinmemberDamian J. Suess4:46 21 Feb '12  
AnswerRe: Good job! PinmemberJuan R. Huertas8:09 21 Feb '12  
GeneralMy vote of 2 PinmemberDean Oliver8:19 1 Feb '12  
GeneralRe: My vote of 2 PinmemberJuan R. Huertas8:34 1 Feb '12  
GeneralRe: My vote of 2 Pinmemberper-i20:50 1 Mar '12  
GeneralRe: My vote of 2 Pinmvpthatraja0:08 9 Mar '12  
QuestionWhen using dialogs test whether the user closed the dialog by OK or Cancel button Pinmembermaskrtnik016:42 1 Feb '12  
AnswerRe: When using dialogs test whether the user closed the dialog by OK or Cancel button PinmemberJuan R. Huertas7:06 1 Feb '12  

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.

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120517.1 | Last Updated 21 Feb 2012
Article Copyright 2012 by Juan R. Huertas
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid