Note: This question is created to help others find what I could not find, having said that anyone is welcome to propose a better solution than I came up with.
My challenge was to produce a smooth scrolling text stream on a windows form application, in addition the form had other items drawn on it so I had to avoid destroying them in the process.
I tried moving a text box incrementing it with timers and do...loops
and so on, also tried using Graphics.DrawString
again incrementing the position.
All of them produced a jerky output with the text flashing as it moved.
I Spent several hours googling and browsing probably in the region of 50 different proposed solutions including many in other languages in the hope I might get a clue!
I can't identify which one gave me the clue but I saw several references to Doublebuffer
so I googled that (and tried it without sucess!) and finally came up with the idea from here of a manual buffer so I ended up with....(see answer below)
Do
Dim currentContext As BufferedGraphicsContext
Dim myBuffer As BufferedGraphics
' Gets a reference to the current BufferedGraphicsContext.
currentContext = BufferedGraphicsManager.Current
' Creates a BufferedGraphics instance associated with Form1, and with
' dimensions the same size as the drawing surface of Form1.
myBuffer = currentContext.Allocate(BNP1.CreateGraphics, BNP1.DisplayRectangle)
'update test
With myBuffer
.Graphics.Clear(Panel.BackColor)
.Graphics.DrawString("Some Text", [Your Font], Brushes.Blue, xpos, ypos)
End With
myBuffer.Render()
myBuffer.Dispose()
'This bit will need adjusting to suit your layout!
If xpos + Panel.Width < Panel.Left Then xpos = Panel.Right Else xpos -= 1
Thread.Sleep(1)
Loop
This produced a perfectly smooth scroll with a fully adjustable scroll speed using the sleep time and xpos reduction.
As you will probably notice I did this with a Do...Loop
in a separate thread it also works in a timer but the scroll speed for some reason (someone can probably explain) is much slower.
Disclaimer: I am not a professional coder so if anyone has suggestions to improve what I have done I will greatly appreciate it (avoid generics such as Option Strict
- already on!)