Using a timer control in Visual F#

Posted by Rey Dacoco in

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:

let timerobjvariable=new Timer()
For instance:
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 “:
// Learn more about F# at http://fsharp.net
//use the F# library
open System
//use this to enable the intellisense. Very helpful in coding your application
open System.Drawing 
//specify the location of the Form classes
open System.Windows.Forms
//creates a form
let timerform=new Form(Text="Use Timer",StartPosition=FormStartPosition.CenterScreen,AutoScaleMode=AutoScaleMode.Font)
//use the random function to generate random numbers
let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 220))
let random=new Random()
//create a timer object and set its interval to 1 second
//by default timer are disabled so you'll need to enable it
let timer1=new Timer(Interval=1000,Enabled=true)
//assigns a random backcolor to our form 
//change it every 1 second
timer1.Tick.Add(fun time->timerform.BackColor<-Color.FromArgb(random.Next(0,255),random.Next(0,255),random.Next(0,255)))
//adds the exit button to our form
timerform.Controls.Add(exitbutton)
//when the exit button is clicked
exitbutton.Click.Add(fun quit->
//stops the time
timer1.Stop()
//close the form
timerform.Close())                   
//show our form
timerform.Show()
//execute our application
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

Contributor

My photo
I am just a simple man with a simple mind. And this is my simple blog. New Posts will be available soon. Enjoy reading and never stop learning:)

Total Pageviews

Link List

Archives

Got questions? You can reach me here: