VB.Net CF Scrolling textbox

It took me awhile to figure this one out.  I needed a textbox that would scroll the text off the left side of the textbox.  It also needed to be able to have more than one string to display.  It would cycle through the strings, changing from the current string to the next string when the current string has scrolled off the screen.

I was able to find a lot of examples on the Net, but none of them worked quite right.  One didn’t work at all, one caused the program to crash while debugging (which kicked VS out of debug mode like I had clicked stop debug!), and the last one worked, but did not meet my requirements.  The one that worked scrolled the text to the right.  And it had some interesting code to it.  That example was found here .

What I came up with was a UserControl as follows:

  Private mStartPos As Integer
  Private mText As Collection
  Private mTextNum As Integer = 1
  Private mScrollSpeed As Integer = 1

Public Sub New()
  ' This call is required by the Windows Form Designer.
  InitializeComponent()
  mText = New Collection()
  mStartPos = 0
  Timer1.Enabled = True
End Sub

This sets up the form. I added a Timer to the designer that is used to update the scrolling. There are also some public accessor subs/properties:

Public Sub AddMarqueeText(ByVal str As String)
  If str <> "" Then
    mText.Add(str, str)
  End If
End Sub

Public Sub RemoveMarqueeText(ByVal str As String)
  If str <> "" Then
    mText.Remove(str)
  End If
End Sub

Public Property ScrollSpeed() As Integer
  Get
    Return mScrollSpeed
  End Get
  Set(ByVal value As Integer)
    If value < 1 Then
      mScrollSpeed = 1
    ElseIf value > 10 Then
      mScrollSpeed = 10
    Else
      mScrollSpeed = value
    End If
    Timer1.Interval = mScrollSpeed * 10
  End Set
End Property

These should be pretty self explanatory. Now the code for the Timer Tick event and Paint event:

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
  If mStartPos >= CStr(mText(mTextNum)).Length Then
    'Change to the next text
    If mTextNum = mText.Count Then
      mTextNum = 1
    Else
      mTextNum += 1
    End If
    mStartPos = 1
  Else
    mStartPos += 1
  End If
  Invalidate()
End Sub

Private Sub ScrollingTextBox_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint
  Dim str As String = CStr(mText.Item(mTextNum))
  Dim g As Graphics = e.Graphics
  Dim tmpStr As String = str.Substring(mStartPos)
  g.DrawString(tmpStr, Me.Font, New SolidBrush(Me.ForeColor), 0, 0)
End Sub

And there you have it. A simple CompactFramework UserControl that holds a collection of strings, scrolls the text as needed, and changes the text that it is displaying.  Right now I am using VS2008 and v3.5 of the CF.Net, but I don’t think there is anything in here that is version specific.