Background Fill

Highlights a rectangle region without changing the text


Imports System.Drawing

Public Class Form6
    Inherits Form

    Private WithEvents rtb As New RichTextBox()

    Public Sub New()
        Me.Text = "BackFill Simulator"
        Me.Size = New Size(800, 600)

        rtb.Dock = DockStyle.Fill
        rtb.Font = New Font("Consolas", 12) ' Fixed-width font for grid
        rtb.Multiline = True
        rtb.WordWrap = False
        rtb.ScrollBars = RichTextBoxScrollBars.Both

        Me.Controls.Add(rtb)

        InitializeText(20, 50)
        BackFill(5, 10, 4, 20, Color.Yellow)
    End Sub

    ' Fill the RichTextBox with placeholder text to simulate a grid
    Private Sub InitializeText(rows As Integer, cols As Integer)
        rtb.Clear()
        For i = 0 To rows - 1
            rtb.AppendText(New String("A"c, cols) & vbCrLf)
        Next
    End Sub

    ' Simulates BackFill: highlights a rectangle region without changing the text
    Public Sub BackFill(R As Integer, C As Integer, H As Integer, W As Integer, attributeColor As Color)
        Dim lines() As String = rtb.Lines

        For row = R To R + H - 1
            If row >= lines.Length Then Exit For

            Dim line = lines(row)
            Dim startCol = Math.Min(C, line.Length)
            Dim endCol = Math.Min(C + W, line.Length)

            Dim startIndex As Integer = rtb.GetFirstCharIndexFromLine(row) + startCol
            Dim length As Integer = Math.Max(0, endCol - startCol)

            If startIndex >= 0 AndAlso (startIndex + length) <= rtb.TextLength Then
                rtb.Select(startIndex, length)
                rtb.SelectionBackColor = attributeColor
            End If
        Next

        rtb.Select(0, 0) ' Deselect
    End Sub

End Class

Download 'Backfill':

📥 Download backfill.vb