Using a timer control in Visual F#

Timer controls are used to automatically execute an action after a specified time has elapsed. To create a timer control in F#, use the following syntax:
  1. let timerobjvariable=new Timer()  
For instance:
  1. let timer=new Timer()  
For a simple example on using a timer control, follow these steps:

1. Click Start>All Programs>Microsoft Visual Studio 2008>Microsoft Visual Studio 2008.

2. Click File>New>Project>Select Visual F# in the project types>Select F# application in the Visual Studio installed templates category.

3. Click the Project menu>Add reference>Click the .Net tab>Locate then double-click System.Windows.Forms.
Do step 3 again and this time, select System.Drawing from the .Net tab.

4. Enter the following code after the line “// Learn more about F# at http://fsharp.net “:
  1. // Learn more about F# at http://fsharp.net  
  2. //use the F# library  
  3. open System  
  4. //use this to enable the intellisense. Very helpful in coding your application  
  5. open System.Drawing   
  6. //specify the location of the Form classes  
  7. open System.Windows.Forms  
  8. //creates a form  
  9. let timerform=new Form(Text="Use Timer",StartPosition=FormStartPosition.CenterScreen,AutoScaleMode=AutoScaleMode.Font)  
  10. //use the random function to generate random numbers  
  11. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 220))  
  12. let random=new Random()  
  13. //create a timer object and set its interval to 1 second  
  14. //by default timer are disabled so you'll need to enable it  
  15. let timer1=new Timer(Interval=1000,Enabled=true)  
  16. //assigns a random backcolor to our form   
  17. //change it every 1 second  
  18. timer1.Tick.Add(fun time->timerform.BackColor<-Color.FromArgb(random.Next(0,255),random.Next(0,255),random.Next(0,255)))  
  19. //adds the exit button to our form  
  20. timerform.Controls.Add(exitbutton)  
  21. //when the exit button is clicked  
  22. exitbutton.Click.Add(fun quit->  
  23. //stops the time  
  24. timer1.Stop()  
  25. //close the form  
  26. timerform.Close())                     
  27. //show our form  
  28. timerform.Show()  
  29. //execute our application  
  30. Application.Run(timerform)  

5. Click the run icon to execute your application. You should now see an output similar to the following screen shot:



If you want a more in depth explanation on this controls, visit the MSDN website at msdn.microsoft.com or the Microsoft F# Development Center at http://msdn.microsoft.com/en-us/fsharp/default.aspx