Reputation:
With the code below I am trying to print i in the textbox every second, but it doesn't update the textbox. Am I missing something?
open System
open System.Drawing
open System.Windows.Forms
open System.Threading
let form = new Form()
let textBox = new TextBox()
textBox.Text <- "Hello, World."
form.Controls.Add textBox
Application.Run form
let rec main i =
Thread.Sleep(1000)
textBox.Text <- sprintf "Hello, World. %i" i
form.Controls.Add textBox
main (i + 1)
main 0
Upvotes: 0
Views: 730
Reputation: 236228
You should use System.Windows.Forms.Timer
if you want to periodically update something on the form. Provide the desired interval of timer ticks, add a Tick
event handler (which updates text in the text box), and start the timer:
let form = new Form()
let textBox = new TextBox(Text = "Hello, world.")
form.Controls.Add textBox
let mutable value = 0 // counter
let timer = new Timer(Interval = 1000) // this timer will fire tick events each second
timer.Tick.Add <| fun _ -> // you can ignore argument which is passed to handler
value <- value + 1
textBox.Text <- sprintf "Hello, World. %i" value
timer.Start()
Application.Run(form)
Why your sample does not work? First of all Application.Run
blocks further execution until you close the opened form. But even if you'll use form.Show()
to execute recursive function while the form is shown, you would see the form stuck and didn't update. Because you are freezing main thread by Thread.Sleep
and form is not able to process events and repaint itself. form.Refresh()
would allow you to see the updates, but between them, the form will be non-responsive. Also, you don't need to add textBox
to form controls on each iteration.
Upvotes: 2