Example 18: Race to Ten Text-Based Game

Problem: Make a simple Race to Ten text-based game. The details of the game is shown in the following screenshot:



Code:
// Learn more about F# at http://fsharp.net
open System
//change the console title
System.Console.Title<-"Race to Ten"
//adds the foreground and background color
System.Console.ForegroundColor<-ConsoleColor.DarkBlue
System.Console.BackgroundColor<-ConsoleColor.Gray
//clears the screen. This is to apply the background color once the
//console application is loaded
System.Console.Clear()
//display the game title screen
printfn "\t\t\t\tRace to Ten"
printfn "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\t\tPress any key to continue..."
System.Console.ReadLine()|>ignore
System.Console.Clear()
//display the game description screen
printfn "Instructions:"
printfn "In this game, each player(you vs. the computer) enters a number between 1 to 3"
printfn "The previously inputted number will be added to the present number"
printfn "The first player to enter a number that adds up to 10 wins the game"
printfn "Press Esc to quit the game"
printfn "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\t\tPress any key to continue..."

let mutable userkey=System.Console.ReadLine()
System.Console.Clear()
//declares our variables
let rndnum=new Random()
let mutable intsum=0
let mutable intusernum=0
let mutable intremain=0
//loop while sum is not equal to 10 and 
//the spacebar key has been pressed
while (intsum < 10 ) do
//computer generates a number
        printfn "\n\nAI's turn..."
        let intainum=rndnum.Next(1,3)
        printfn "AI num: %d" intainum
//accumulates the number to the
//value of sum
        intsum<-intsum + intainum
        printfn "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\t\tPress any key to continue...Esc to quit"
        System.Console.ReadLine()|>ignore
System.Console.Clear()
//display how many numbers more to go
//before 10
intremain<-intsum-10  
        printfn "%d more to go!" intremain
 //if the sum is equal to 10 
 //display "computer wins"
        if intsum>=10 then  
System.Console.Clear()
//reset the value of sum so that 
//the game will loop again
//remove intsum<-0 if you want the
 //game to end after one game
            printfn "Computer Wins!" 
            intsum<-0
            printfn "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\t\tPress any key to continue...Esc to quit"
            System.Console.ReadLine()|>ignore
System.Console.Clear()          
//otherwise ask for a number         
printfn "\n\nYour turn:" 
intusernum<-(int)(System.Console.ReadLine())
 //if the number exceeds 3 then
 //ask for a number again
        if intusernum>3 then
printfn "Number must be between 1 to 3"
printfn "You turn:"
intusernum<-(int)(System.Console.ReadLine())
            intsum<-intsum + intusernum
            System.Console.Clear()
//accumulates the inputted number to the value of sum
        intsum<-intsum + intusernum 
        intremain<-intsum-10  
        printfn "%d more to go!" intremain
        if intsum>=10 then
System.Console.Clear()
printfn "You Win!"
intsum<-0
            printfn "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\t\tPress any key to continue...Esc to quit"
            System.Console.ReadLine()|>ignore
System.Console.Clear()

Example#17(Array.Iter)

Problem: Make a console application that will convert the following singular nouns to plural. Use Array.Iter:

1. ally
2. army
3. baby
4. lady
5. navy

// Learn more about F# at http://fsharp.net
open System
//change the console title
System.Console.Title<-"Convert to Plural"
//adds the foreground and background color
System.Console.ForegroundColor<-ConsoleColor.Blue
System.Console.BackgroundColor<-ConsoleColor.White
//clears the screen. This is to apply the background color once the
//console application is loaded
System.Console.Clear()
//assigns the singular nouns to our array variable singularnouns
let singularnouns=[|"ally";"army";"baby";"lady";"navy"|]
printfn "Singular words:"
//iterates through the values of our singularnouns array variable
singularnouns|>Array.iter(fun singularwords->printfn "%s" singularwords)
printfn "Plural words:"
//iterates through the values of our singularnouns array variable
//replace the word in each array element from "y" to "ies"
singularnouns|>Array.iter(fun pluralnouns->
let pluralwords= pluralnouns.Replace("y","ies")
printfn "%s" pluralwords)

This will display the following output:

Visual F# 100 Examples: Example Number 16(Search a Record Value)

Problem: Make a Windows Forms Application that will allow the user to search a record value from a database file.

// Learn more about F# at http://fsharp.net
//specifies the memory location of the class files
//that will be needed in our application
open System.Collections.Generic
open System
open System.Windows.Forms
open System.ComponentModel
open System.Data
open System.Drawing
open System.Data.OleDb
//creates a font
let ffont=new Font("Verdana", 9.75F,FontStyle.Regular, GraphicsUnit.Point)  
//creates a connection object
let oleconn = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;
  Data Source=C:\Documents and Settings\Station03\My Documents\dbEmployee.mdb")
 //creates an OleDbDataAdapter
let dataadpter = new System.Data.OleDb.OleDbDataAdapter("Select * from tblEmployee", oleconn)
//generates a dataset
let dataset11 = new DataSet()
//fills the dataset with recod values
dataadpter.Fill(dataset11,"tblEmployee")|>ignore
//creates a form
let dataform = new Form(Text="Search a Record Value",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(400, 360),StartPosition=FormStartPosition.CenterScreen)
//creates our controls
let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(300, 320)) 
let searchbutton=new Button(Text="Search", Location=new System.Drawing.Point(220, 320))  
let label1=new Label(Text="Enter the employee number:",Location=new System.Drawing.Point(0, 10),AutoSize=true)
let label2=new Label(Text="Empno:",Location=new System.Drawing.Point(0, 50),AutoSize=true)
let label3=new Label(Text="Firstname:",Location=new System.Drawing.Point(0,100),AutoSize=true)
let label4=new Label(Text="Lastname:",Location=new System.Drawing.Point(0,150),AutoSize=true)
let empnotext=new TextBox(Location=new System.Drawing.Point(200,10))
let emplabel=new Label(Location=new System.Drawing.Point(100,50),BorderStyle=BorderStyle.FixedSingle)
let fnamelabel=new Label(Location=new System.Drawing.Point(100,100),BorderStyle=BorderStyle.FixedSingle)
let lnamelabel=new Label(Location=new System.Drawing.Point(100,150),BorderStyle=BorderStyle.FixedSingle)
//creates a datagrid
let datagrid = new DataGridView(ColumnHeadersHeightSizeMode=DataGridViewColumnHeadersHeightSizeMode.AutoSize,Size=new System.Drawing.Size(300, 120),Location=new System.Drawing.Point(10, 180))
//creates a grid control colums
let chrempnocol=new DataGridViewTextBoxColumn()
let chrfnamecol=new DataGridViewTextBoxColumn()
let chrlnamecol=new DataGridViewTextBoxColumn()
//adds the columns into our datagrid
datagrid.Columns.Add(chrempnocol)|>ignore
datagrid.Columns.Add(chrfnamecol)|>ignore
datagrid.Columns.Add(chrlnamecol)|>ignore
datagrid.DataSource <- dataset11.Tables.["tblEmployee"]
//assingns the font to our form
dataform.Font<-ffont
//links our fieldname to each grid
//and change its header text
chrempnocol.DataPropertyName<-"chrempno"
chrempnocol.HeaderText<-"Employee No."
chrfnamecol.DataPropertyName<-"chrfname"
chrfnamecol.HeaderText<-"First Name"
chrlnamecol.DataPropertyName<-"chrlname"
chrlnamecol.HeaderText<-"Last Name"
//add the datagrid to our form
dataform.Controls.Add(datagrid)
//adds the controls to our form
dataform.Controls.Add(exitbutton)
dataform.Controls.Add(searchbutton)
dataform.Controls.Add(label1)
dataform.Controls.Add(label2)
dataform.Controls.Add(label3)
dataform.Controls.Add(label4)
dataform.Controls.Add(empnotext)
dataform.Controls.Add(emplabel)
dataform.Controls.Add(fnamelabel)
dataform.Controls.Add(lnamelabel)
//binds the fieldnames to our label
emplabel.Text<-Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(0).Item(0))
fnamelabel.Text<-Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(0).Item(1))
lnamelabel.Text<-Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(0).Item(2))
searchbutton.Click.Add(fun search->  
                    //handles the row index number               
                    let mutable introws=0
                    //determines if the record has been found or not
                    let mutable blnfound=false   
                    //handles the total number of records                
                    let mutable inttotrec=Convert.ToInt32(dataset11.Tables.["tblEmployee"].Rows.Count)
                    //handles the data inputted by the user
                    let strtext=Convert.ToString(empnotext.Text)
                    //while no match is found and the end of the file has not been reached
                    while((blnfound=false) && (introws<=inttotrec-1)) do
                         let strempnum=Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(introws).Item(0))
                         //compare the data inputted in the textbox to the employee number in our table
                         //if they are equal, display the match record
                         if strtext.ToUpper()=strempnum.ToUpper() then
                            blnfound<-true
                            emplabel.Text<-Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(introws).Item(0))
                            fnamelabel.Text<-Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(introws).Item(1))
                            lnamelabel.Text<-Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(introws).Item(2)) 
                         //compare to the next record while no match is found
                         introws<-introws + 1    
                    //if no match is found, display this      
                    if blnfound=false then
                        MessageBox.Show("Record not found.","Search a Record Value",MessageBoxButtons.OK,MessageBoxIcon.Information)|>ignore)                       
//when the exit button is clicked
exitbutton.Click.Add(fun exit->
//close the form and dataconnection
                    dataform.Close()
                    oleconn.Close()) 
//executes our application
Application.Run(dataform)

Since Visual F# is very particular with the code indention, I posted below the screenshot of our code in the while loop section.



Here's what it should look like if you click the run icon:

Visual F# 100 Examples: Example 14 and 15(Pattern Matching)

Pattern matching/match with statement is similar to the switch selection statement in other programming languages. The following examples demonstrate how to use it:


Problem: Make an application that will asks a letter and displays its equivalent U. S. military phonetic alphabet.
//use F# library
open System
//change the CLI title
System.Console.Title<-"Display Military Phoenitic Alphabet"
//adds color to our console application
System.Console.ForegroundColor<-ConsoleColor.Blue
//asks the user to enter a letter
printfn "Enter a letter:"
//convert the input to character and convert it to uppercase letter
//this is just for comparison purpose
let chrletter=Char.ToUpper(Convert.ToChar(System.Console.ReadLine()))
//clear the screen   
System.Console.Clear()
//match the value of chrletter to the ff. values
match chrletter with
//if the value of chrletter is a or A display Alpha
| 'A' ->printfn "Alpha"
//if the value of chrletter is b or B display Bravo
| 'B' ->printfn "Bravo"
//if the value of chrletter is c or C display Charlie
| 'C' ->printfn "Charlie"
//if the value of chrletter is d or D display Delta
| 'D' ->printfn "Delta"
//if the value of chrletter is e or E display Echo
| 'E'->printfn "Echo"
//if the value of chrletter is f or F display Foxtrot
| 'F'->printfn "FoxTrot"
//if the value of chrletter is g or G display Golf
| 'G'->printfn "Golf"
//if the value of chrletter is h or H display Hotel
| 'H'->printfn "Hotel"
//if the value of chrletter is i or I display India
| 'I'->printfn "India"
//if the value of chrletter is j or J display Juliet
| 'J'->printfn "Juliet"
//if the value of chrletter is k or K display Kilo
| 'K'->printfn "Kilo"
//if the value of chrletter is l or L display Lima
| 'L'->printfn "Lima"
//if the value of chrletter m or M display Mike
| 'M'->printfn "Mike"
//if the value of chrletter is n or N display November
| 'N'->printfn "November"
//if the value of chrletter is o or O display Oscar
| 'O'->printfn "Oscar"
//if the value of chrletter is p or P display Papa
| 'P'->printfn "Papa"
//if the value of chrletter is q or Q display Quebec
| 'Q'->printfn "Quebec"
//if the value of chrletter is r or R display Romeo
| 'R'->printfn "Romeo"
//if the value of chrletter is s or S display Sierra
| 'S'->printfn "Sierra"
//if the value of chrletter is t or T display Tango
| 'T'->printfn "Tango"
//if the value of chrletter is u or U display Uniform
| 'U'->printfn "Uniform"
//if the value of chrletter is v or V display Victor
| 'V'->printfn "Victor"
//if the value of chrletter is w or W display Whiskey
| 'W'->printfn "Whiskey"
//if the value of chrletter is x or X display X-Ray
| 'X'->printfn "X-Ray"
//if the value of chrletter is y or Y display Yankee
| 'Y'->printfn "Yankee"
//if the value of chrletter is z or Z display Zulu
| 'Z'->printfn "Zulu"
//otherwise
| _ ->printfn "Invalid input"
The last statement |_ is similar to the
default statement in other programming languages Switch conditional structure. It is automatically executed when no pattern match is found. Don't forget to add it at the end of every match with statement otherwise you will get an “Incomplete pattern matches on this expression” error.


Problem: Make an application that will ask the month number and display the corresponding month name and the number of days in it. Use pattern matching.

//use F# library
open System
//change the CLI title
System.Console.Title<-"Display Month Name"
//adds color to our console application
System.Console.ForegroundColor<-ConsoleColor.Blue
System.Console.BackgroundColor<-ConsoleColor.White
//asks the user to enter a month number
printfn "Enter a month number(1-12):"
let intmonth=Convert.ToInt32(System.Console.ReadLine())
//clear the screen   
System.Console.Clear()
//match the value of intmonth to the ff. values
match intmonth with
//if the value of intmonth is 1 display January
| 1 ->printfn "January(31 days)"
//if the value of intmonth is 2 display February
| 2 ->printfn "Febrary(28/29 days)"
//if the value of intmonth is 3 display March 
| 3 ->printfn "March(31 days)"
//if the value of intmonth is 4 display April
| 4 ->printfn "April(30 days)"
//if the value of intmonth is 5 display May
| 5 ->printfn "May(31 days)"
//if the value of intmonth is 6 display June
| 6 ->printfn "June(30 days)"
//if the value of intmonth is 7 display July
| 7 ->printfn "July(31 days)"
//if the value of intmonth is 8 display August
| 8 ->printfn "August(31 days)"
//if the value of intmonth is 9 display September
| 9 ->printfn "September(30 days)"
//if the value of intmonth is 10 display October
| 10 ->printfn "October(31 days)"
//if the value of intmonth is 11 display November
| 11 ->printfn "November(30 days)"
//if the value of intmonth is 12 display December
| 12->printfn "December(31 days)"
//otherwise
| _ ->printfn "Invalid input"

That's all for now my Visual F# friends. Ciao!

Visual F# 100 Examples: Example 12 and 13

This is the continuation of our planned 100 Visual F# examples. By the way, the bugs in examples number 7 to 11 had been fixed. My apologies, I should’nt have written those without using Visual F# compiler:)


Problem: Make a console application that will asks the user to enter the day that he was born and display his character or future based on the famous nursery rhyme written in England, “Monday’s Child”.

open System
//changes the console application title
System.Console.Title<-"Tell the Future"
//adds foreground color
System.Console.ForegroundColor<-ConsoleColor.Cyan
printfn "What day were you born?"
let strday=System.Console.ReadLine()
//clears the screen
System.Console.Clear()
//converts the inputs to lowercase then compare it our
//specified values
if strday.ToLower()="monday" then
    printfn "Monday's child is fair of face"
else if strday.ToLower()="tuesday" then
    printfn "Tuesday's child is full of grace"
else if strday.ToLower()="wednesday" then
    printfn "Wednesday's child is full of woe"
else if strday.ToLower()="thursday" then
    printfn "Thurdays's child has far to go"
else if strday.ToLower()="friday" then
    printfn "Friday's child is loving and giving"
else if strday.ToLower()="saturday" then
    printfn "Saturday's child works hard for a living"
else if strday.ToLower()="sunday" then
    printfn "Sunday's child is bonny and blithe and good and gay"
else
    printfn "Invalid input"
Problem: Develop a console application that will asks the wind speed in kilometer per hour(kph) and display its equivalent Philippine Storm Signal number.
open System
//changes the console application title
System.Console.Title<-"Determine Storm Signal Number"
//adds foreground color
System.Console.ForegroundColor<-ConsoleColor.Cyan
printfn "Enter wind speed(kph):"
let intspeed=Convert.ToInt32(System.Console.ReadLine())
//clears the screen
System.Console.Clear()
//if the wind speed ranges from 30 to 60
if intspeed>=30 && intspeed<=60 then
    printfn "Storm signal number 1"
//if the wind speed ranges from 61 to 100
else if intspeed>60 && intspeed<=100 then
    printfn "Storm signal number 2"
//if the wind speed ranges from 101 to 185
else if intspeed>100 && intspeed<=185 then
    printfn "Storm signal number 3"
//if the wind speed is greater than 185
else if intspeed>185 then
printfn "Storm signal number 4"
else 
printfn "Invalid input"

Visual F# 100 Examples: Example 11

Problem: Make a simple crack the treasure chest console application game.

// Learn more about F# at http://fsharp.net

open System
//change the title to Crack the Safe
System.Console.Title<-"Crack the Safe"
//change the foreground color to green
Console.ForegroundColor<-ConsoleColor.Green
//dislay the game title screen
printfn "\t\t\t Crack the Safe"
printfn "\t\t\t Press enter to continue..."
//waits for a keypress from the user
System.Console.ReadLine()|>ignore
//Game action sequence
printfn "\t\t\t You have found a legendary treasure chest"
printfn "\t\t\t believed to contain the rarest gem on Earth"
printfn "\t\t\t Press enter to continue... "
//waits for a keypress from the user
System.Console.ReadLine()|>ignore

printfn "\t\t\t this chest can be opened only by"
printfn "\t\t\t entering a mysterious 4-digit key code"
printfn "\t\t\t Press enter to continue..."
//waits for a keypress from the user
System.Console.ReadLine()|>ignore

let random=new Random()
let intkeycode=Convert.ToInt32(random.Next(1000,9999))

printfn "\t\t\tEnter the keycode:"
let intusercode= Convert.ToInt32(Console.ReadLine())
//if usercode is equal to the computer generated code then
if intusercode=intkeycode then
//display a congratulatory message
    printfn "\t\t\Congrats You have opened the treasure chest."

//otherwise 
else
    printfn "\t\t\tInvalid Code"

printfn "\t\t\tPress enter to continue... "
System.Console.ReadLine()|>ignore
printfn "\t\t\tGame Over"

Visual F# 100 Examples: Example 8 to 10

Problem: Make a console application that will accept five numbers and display the sum.
open System
//change the title to Add Five Numbers
System.Console.Title<-"Add Five Numbers "
//change the foreground color to cyan
Console.ForegroundColor<-ConsoleColor.Cyan
printfn "\t\t\tEnter the first number:"
let intnum1=Convert.ToInt32(System.Console.ReadLine())
printfn "\t\t\tEnter the second number:"
let intnum2=Convert.ToInt32(System.Console.ReadLine())
printfn "\t\t\tEnter the third number:"
let intnum3=Convert.ToInt32(System.Console.ReadLine())
printfn "\t\t\tEnter the fourth number:"
let intnum4=Convert.ToInt32(System.Console.ReadLine())
printfn "\t\t\tEnter the fifth number:"
let intnum5=Convert.ToInt32(System.Console.ReadLine())
let  intsum=intnum1+ intnum2 + intnum3 + intnum4 + intnum5
printfn "\t\t\tThe sum is:%i" intsum

Problem: Make a console application that will ask the power transmitted and power received then display the power loss value.
open System
//change the title to Calculate Power Loss
System.Console.Title<-"Calculate Power Loss "
//change the foreground color to cyan
Console.ForegroundColor<-ConsoleColor.Cyan
printfn "\t\t\t\tPower transmitted:"
let dblpowertrans=Convert.ToDouble(System.Console.ReadLine())
printfn "\t\t\tPower recieved:"
let dblpowerrec=Convert.ToDouble(System.Console.ReadLine())
let dblpowerloss= dblpowertrans/ dblpowerrec
printfn "\t\t\t Power loss:%f " dblpowerloss

Problem: Develop a console application that will ask the base value and height value then display the volume of a pyramid.
open System
//change the title to Volume of a Pyramid
System.Console.Title<-" Volume of a Pyramid"
//change the foreground color to cyan
Console.ForegroundColor<-ConsoleColor.Cyan
printfn "\t\t\tBase value:"
let dblbase=Convert.ToDouble(System.Console.ReadLine())
printfn "\t\t\tHeight value:"
let dblheight=Convert.ToDouble(System.Console.ReadLine())
let  dblvolume=(dblbase*dblheight)/3.0
printfn "\t\t\tVolume of a pyramid:%f" dblvolume

Visual F# 100 Examples: Example Number 7

So far I have been sharing to you guys some examples of Window Based application in Visual F#. This time, for variation sake lets make some console application:

Problem: Make a simple console application mind reader game.
open System
//change the title to Simple Mind Reader Game
System.Console.Title<-"Simple Mind Reader Game"
//change the foreground color to cyan
Console.ForegroundColor<-ConsoleColor.Cyan
//dislay the game title screen
printfn "\t\t\t Mind Reader Game"
printfn "\t\t\tPress enter to continue..."
//waits for a keypress from the user
System.Console.ReadLine()|>ignore
System.Console.Clear()
//the following does the game action sequence
printfn "\t\t\t Think of a five-digit number that has five unique numbers(Eg. 12345)"
printfn "\t\t\tPress enter to continue..."
System.Console.ReadLine()|>ignore
System.Console.Clear()

printfn "\t\t\t Reverse the numbers then subtract the smaller number from the larger number(Eg.54321- 12345)"
printfn "\t\t\tPress enter to continue..."
System.Console.ReadLine()|>ignore
System.Console.Clear()

printfn "\t\t\t Add 10000 to the difference"
printfn "\t\t\t Press enter to continue..."
System.Console.ReadLine()|>ignore
System.Console.Clear()

printfn "\t\t\tVisualize the sum while I try to read your mind."
printfn "\t\t\tPress enter to continue..."
System.Console.ReadLine()|>ignore
System.Console.Clear()

printfn "\t\t\tThe sum is…"
printfn "\t\t\tPress enter to continue..."
System.Console.ReadLine()|>ignore
System.Console.Clear()

printfn "\t\t\tThe sum is…"
printfn "\t\t\tPress enter to continue..."
System.Console.ReadLine()|>ignore
System.Console.Clear()

printfn "\t\t\tThe sum is…"
printfn "\t\t\tPress enter to continue..."
System.Console.ReadLine()|>ignore
System.Console.Clear()

printfn "\t\t\t51976"

Visual F# 100 Examples: Example Number 6

Problem. Create an application that will display the surface area of a cube. The surface area of a cube can be computed by multiplying the inputted side by itself and multiplying the product by 6.
// Learn more about F# at http://fsharp.net
//specifies the memory location of the class files
//that will be needed in our application
open System.Collections.Generic
open System
open System.Windows.Forms
open System.ComponentModel
open System.Drawing
//creates a new form
let cubeform=new Form(Text="Compute the Surface Area of a Cube", Size=new System.Drawing.Size(300, 200),StartPosition=FormStartPosition.CenterScreen,AutoScaleMode=AutoScaleMode.Font)
//creates our controls
let n1label=new Label(Text="Enter a side value:",Location=new System.Drawing.Point(0,20),AutoSize=true)
let firsttextbox=new TextBox(Location=new System.Drawing.Point(120, 20))
let n2label=new Label(Text="Surface area of a cube:", Location=new System.Drawing.Point(0, 90),AutoSize=true)
//creates a label that will display the result of the computation
let anslabel=new Label(Location=new System.Drawing.Point(140, 90), BorderStyle=BorderStyle.FixedSingle)
//make our buttons
let computebutton=new Button(Text="Compute", Location=new System.Drawing.Point(100, 130))
let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 130))
//add the controls into the form
cubeform.Controls.Add(n1label)
cubeform.Controls.Add(firsttextbox)
cubeform.Controls.Add(n2label)
cubeform.Controls.Add(anslabel)
cubeform.Controls.Add(computebutton)
cubeform.Controls.Add(exitbutton)

//when the compute button is clicked
computebutton.Click.Add(fun ans->
let sidevalue=Convert.ToDouble(firsttextbox.Text)
let areaofacube=6.00*(sidevalue*sidevalue)

//display the areaofacube value in the anslabel
anslabel.Text<-Convert.ToString(areaofacube))
 //when the exit button is clicked, close the form            
exitbutton.Click.Add(fun exit -> cubeform.Close())  
Application.Run(cubeform)

We'll be adding some new controls after our tenth example:)

Visual F# 100 Examples:Example Number 5

Problem: Design an application that will ask a length value, height value, and width value and display the volume of the prism.
// Learn more about F# at http://fsharp.net
//specifies the memory location of the class files
//that will be needed in our application
open System.Collections.Generic
open System
open System.Windows.Forms
open System.ComponentModel
open System.Drawing
//creates our controls
let prismform=new Form(Text="Compute the Volume of a Prism", Size=new System.Drawing.Size(300, 330),StartPosition=FormStartPosition.CenterScreen,AutoScaleMode=AutoScaleMode.Font)
let n1label=new Label(Text="Length value:",Location=new System.Drawing.Point(0,20),AutoSize=true)
let lenghttxtbox=new TextBox(Location=new System.Drawing.Point(80, 20))
let n2label=new Label(Text="Width value:", Location=new System.Drawing.Point(0,50),AutoSize=true)
let widthtxtbox=new TextBox(Location=new System.Drawing.Point(80,50))
let n3label=new Label(Text="Height value:", Location=new System.Drawing.Point(0, 90),AutoSize=true)
let heighttxtbox=new TextBox(Location=new System.Drawing.Point(130, 90))

let n4label=new Label(Text="Prisms volume:", Location=new System.Drawing.Point(0, 180),AutoSize=true)
let prismlabel=new Label(Location=new System.Drawing.Point(130, 180),BorderStyle=BorderStyle.FixedSingle)
let computebutton=new Button(Text="Compute", Location=new System.Drawing.Point(100, 250))
let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 250))

//add the controls into the form
prismform.Controls.Add(n1label)
prismform.Controls.Add(lenghttxtbox)
prismform.Controls.Add(n2label)
prismform.Controls.Add(widthtxtbox)
prismform.Controls.Add(n3label)
prismform.Controls.Add(heighttxtbox)
prismform.Controls.Add(n4label)
prismform.Controls.Add(prismlabel)
prismform.Controls.Add(computebutton)
prismform.Controls.Add(exitbutton)

//when the compute button is clicked
computebutton.Click.Add(fun compute->
//assign the data inputted in each control to each corresponding variables
//compute the volume using the formula volume=lengthvalue*widthvalue*heightvalue
//display the result on outcome on their assigned controls
let lenghtvalue=Convert.ToDouble(lenghttxtbox.Text)
let widthvalue=Convert.ToDouble(widthtxtbox.Text)
let heightvalue=Convert.ToDouble(heighttxtbox.Text)
let prismvol=lenghtvalue*widthvalue*heightvalue
prismlabel.Text<-Convert.ToString(prismvol))
 //when the exit button is clicked, close the form            
exitbutton.Click.Add(fun exit -> prismform.Close())  
Application.Run(prismform)

Visual F# 100 Examples: Example Number 4

Problem: Make an application that will display the area of an annulus (overlapping circles). The area of an annulus can be calculated by subtracting the area of a small circle from the area of a larger circle.

// Learn more about F# at http://fsharp.net
//specifies the memory location of the class files
//that will be needed in our application
open System.Collections.Generic
open System
open System.Windows.Forms
open System.ComponentModel
open System.Drawing
//creates a new form
let annulform=new Form(Text="Dislay the Area of an Annulus", Size=new System.Drawing.Size(300, 200),StartPosition=FormStartPosition.CenterScreen,AutoScaleMode=AutoScaleMode.Font)
//creates our controls
let n1label=new Label(Text="Area of a large circle:",Location=new System.Drawing.Point(0,20),AutoSize=true)
let firsttextbox=new TextBox(Location=new System.Drawing.Point(120, 20))
let n2label=new Label(Text="Area of a small circle:", Location=new System.Drawing.Point(0,50),AutoSize=true)
let secondtextbox=new TextBox(Location=new System.Drawing.Point(120,50))
let n3label=new Label(Text="Area of an annulus:", Location=new System.Drawing.Point(0, 90),AutoSize=true)
//creates a label that will display the result of the computation
let anslabel=new Label(Location=new System.Drawing.Point(120, 90), BorderStyle=BorderStyle.FixedSingle)
//make our buttons
let computebutton=new Button(Text="Compute", Location=new System.Drawing.Point(100, 130))
let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 130))
//add the controls into the form
annulform.Controls.Add(n1label)
annulform.Controls.Add(firsttextbox)
annulform.Controls.Add(n2label)
annulform.Controls.Add(secondtextbox)
annulform.Controls.Add(n3label)
annulform.Controls.Add(anslabel)
annulform.Controls.Add(computebutton)
annulform.Controls.Add(exitbutton)

//when the compute button is clicked
computebutton.Click.Add(fun ans ->
let areaoflargecircle=Convert.ToDouble(firsttextbox.Text)
let areaofsmallcircle=Convert.ToDouble(secondtextbox.Text)
let areaofannulus=areaoflargecircle-areaofsmallcircle

//display the area of annulus value in the anslabel
anslabel.Text<-Convert.ToString(areaofannulus))
 //when the exit button is clicked, close the form            
exitbutton.Click.Add(fun exit -> annulform.Close())  
Application.Run(annulform)

Visual F# 100 Examples:Example Number 3

We are now on our third example of our planned 100 Visual F# windows form applications learning examples. If you noticed we are just using basic controls such as textboxes, labels, and buttons. We will add some new controls in our future examples. Meanwhile, try the following:

Problem: Create an application that will ask the name of an object or material, its voltage and current values then display its electrical resistance.

Solution:
// Learn more about F# at http://fsharp.net
//specifies the memory location of the class files
//that will be needed in our application
open System.Collections.Generic
open System
open System.Windows.Forms
open System.ComponentModel
open System.Drawing
//creates our controls
let resistanceform=new Form(Text="Compute Resistance", Size=new System.Drawing.Size(300, 330),StartPosition=FormStartPosition.CenterScreen,AutoScaleMode=AutoScaleMode.Font)
let n1label=new Label(Text="Material:",Location=new System.Drawing.Point(0,20),AutoSize=true)
let materialtextbox=new TextBox(Location=new System.Drawing.Point(80, 20))
let n2label=new Label(Text="Current(volts):", Location=new System.Drawing.Point(0,50),AutoSize=true)
let currenttextbox=new TextBox(Location=new System.Drawing.Point(80,50))
let n3label=new Label(Text="Voltage(amperes):", Location=new System.Drawing.Point(0, 90),AutoSize=true)
let voltstextbox=new TextBox(Location=new System.Drawing.Point(130, 90))

let n4label=new Label(Text="Material:", Location=new System.Drawing.Point(0, 180),AutoSize=true)
let materiallabel=new Label(Location=new System.Drawing.Point(130, 180),BorderStyle=BorderStyle.FixedSingle)
let n5label=new Label(Text="Resistance(ohms):", Location=new System.Drawing.Point(0, 210),AutoSize=true)
let resistancelabel=new Label(Location=new System.Drawing.Point(130, 210),BorderStyle=BorderStyle.FixedSingle)
let computebutton=new Button(Text="Compute", Location=new System.Drawing.Point(100, 250))
let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 250))

//add the controls into the form
resistanceform.Controls.Add(n1label)
resistanceform.Controls.Add(materialtextbox)
resistanceform.Controls.Add(n2label)
resistanceform.Controls.Add(currenttextbox)
resistanceform.Controls.Add(n3label)
resistanceform.Controls.Add(voltstextbox)
resistanceform.Controls.Add(n4label)
resistanceform.Controls.Add(materiallabel)
resistanceform.Controls.Add(n5label)
resistanceform.Controls.Add(resistancelabel)
resistanceform.Controls.Add(computebutton)
resistanceform.Controls.Add(exitbutton)

//when the compute button is clicked
computebutton.Click.Add(fun compute->
//assign the data inputted in each control to each corresponding variables
//compute the resistance using the formula resistance=voltage divided by current
//display the result on outcome on their assigned controls
let material=materialtextbox.Text
let current=Convert.ToDouble(currenttextbox.Text)
let voltage=Convert.ToDouble(voltstextbox.Text)
let resistance=voltage/current
materiallabel.Text<-material
resistancelabel.Text<-Convert.ToString(resistance))
 //when the exit button is clicked, close the form            
exitbutton.Click.Add(fun exit -> resistanceform.Close())  
Application.Run(resistanceform)

Visual F# 100 Examples: Example Number 2

Last time I have shared to you our first simple example of window forms application using Visual F#, let’s now proceed to our second example:

Problem: Make a windows forms application that will ask the amount of consumption, amount of investment, government spending, amount of exports and imports and display the net emports and Gross Domestic Product (GDP).

Solution:
// Learn more about F# at http://fsharp.net
//specifies the memory location of the class files
//that will be needed in our application
open System.Collections.Generic
open System
open System.Windows.Forms
open System.ComponentModel
open System.Drawing
//creates our controls
let gdpform=new Form(Text="Compute GDP", Size=new System.Drawing.Size(300, 330),StartPosition=FormStartPosition.CenterScreen,AutoScaleMode=AutoScaleMode.Font)
let n1label=new Label(Text="Consumption:",Location=new System.Drawing.Point(0,20),AutoSize=true)
let firsttextbox=new TextBox(Location=new System.Drawing.Point(80, 20))
let n2label=new Label(Text="Investment:", Location=new System.Drawing.Point(0,50),AutoSize=true)
let secondtextbox=new TextBox(Location=new System.Drawing.Point(80,50))
let n3label=new Label(Text="Government spending:", Location=new System.Drawing.Point(0, 90),AutoSize=true)
let thirdtextbox=new TextBox(Location=new System.Drawing.Point(130, 90))
let n4label=new Label(Text="Exports:", Location=new System.Drawing.Point(0, 120),AutoSize=true)
let fourthtextbox=new TextBox(Location=new System.Drawing.Point(130, 120))
let n5label=new Label(Text="Imports:", Location=new System.Drawing.Point(0, 150),AutoSize=true)
let fifthtextbox=new TextBox(Location=new System.Drawing.Point(130, 150))
let n6label=new Label(Text="Imports:", Location=new System.Drawing.Point(0, 180),AutoSize=true)
let netemlabel=new Label(Location=new System.Drawing.Point(130, 180),BorderStyle=BorderStyle.FixedSingle)
let n7label=new Label(Text="GDP:", Location=new System.Drawing.Point(0, 210),AutoSize=true)
let gdplabel=new Label(Location=new System.Drawing.Point(130, 210),BorderStyle=BorderStyle.FixedSingle)
let computebutton=new Button(Text="Compute", Location=new System.Drawing.Point(100, 250))
let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 250))
//add the controls into the form
gdpform.Controls.Add(n1label)
gdpform.Controls.Add(firsttextbox)
gdpform.Controls.Add(n2label)
gdpform.Controls.Add(secondtextbox)
gdpform.Controls.Add(n3label)
gdpform.Controls.Add(thirdtextbox)
gdpform.Controls.Add(n4label)
gdpform.Controls.Add(fourthtextbox)
gdpform.Controls.Add(n5label)
gdpform.Controls.Add(fifthtextbox)
gdpform.Controls.Add(n6label)
gdpform.Controls.Add(netemlabel)
gdpform.Controls.Add(n7label)
gdpform.Controls.Add(gdplabel)
gdpform.Controls.Add(computebutton)
gdpform.Controls.Add(exitbutton)
//when the compute button is clicked
computebutton.Click.Add(fun compute->
//assigned the numbers inputted to each textbox to their corresponding variable
//compute the net emport using the formula net emport=export-import
//compute the gdp using the formula gdp=consumption+investment+govspending+netemport
let consumption=Convert.ToDouble(firsttextbox.Text)
let investment=Convert.ToDouble(secondtextbox.Text)
let govspending=Convert.ToDouble(thirdtextbox.Text)
let export=Convert.ToDouble(fourthtextbox.Text)
let import=Convert.ToDouble(fifthtextbox.Text)
let netemport=export-import
let gdp=(consumption+investment+govspending+netemport)
netemlabel.Text<-Convert.ToString(netemport)
                 gdplabel.Text<-Convert.ToString(gdp))
 //when the exit button is clicked, close the form            
exitbutton.Click.Add(fun exit -> gdpform.Close())  
Application.Run(gdpform)

Visual F# 100 Examples: Example Number 1

Starting today, I will be sharing to you guys some learning examples that will aid you in learning windows forms application programming in Visual F#. Our target is to be able to share at least 100 examples. Let’s start with example number 1:

Problem: Make a windows form application that will ask the user’s mental age and chronological age and display his intelligence quotient (IQ).

Solution:
// Learn more about F# at http://fsharp.net
//specifies the memory location of the class files
//that will be needed in our application
open System.Collections.Generic
open System
open System.Windows.Forms
open System.ComponentModel
open System.Drawing
//creates a new form
let iqform=new Form(Text="Compute IQ", Size=new System.Drawing.Size(300, 200),StartPosition=FormStartPosition.CenterScreen,AutoScaleMode=AutoScaleMode.Font)
//creates a label
let n1label=new Label(Text="Mental age:",Top=20,Left=5,AutoSize=true)
let firsttextbox=new TextBox(Location=new System.Drawing.Point(80, 20))
//creates another label and change its text to “Second number:”
let n2label=new Label(Text="Chronological age:", Location=new System.Drawing.Point(0,50),AutoSize=true)
let secondtextbox=new TextBox(Location=new System.Drawing.Point(100,50))
//creates another label and change its text to sum
let n3label=new Label(Text="IQ:", Location=new System.Drawing.Point(0, 90),AutoSize=true)
//creates a label that will display the result of the computation
let anslabel=new Label(Location=new System.Drawing.Point(80, 90), BorderStyle=BorderStyle.FixedSingle)
//make our buttons
let addbutton=new Button(Text="Compute", Location=new System.Drawing.Point(100, 130))
let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 130))
//add the controls into the form
iqform.Controls.Add(n1label)
iqform.Controls.Add(firsttextbox)
iqform.Controls.Add(n2label)
iqform.Controls.Add(secondtextbox)
iqform.Controls.Add(n3label)
iqform.Controls.Add(anslabel)
iqform.Controls.Add(addbutton)
iqform.Controls.Add(exitbutton)

//when the compute button is clicked
addbutton.Click.Add(fun addfunction ->
let manum=Convert.ToDouble(firsttextbox.Text)
let canum=Convert.ToDouble(secondtextbox.Text)
let iq=Convert.ToDouble((manum/canum)*100.00)

//display the iq value in the anslabel
anslabel.Text<-Convert.ToString(iq))
 //when the exit button is clicked, close the form            
exitbutton.Click.Add(fun exit -> iqform.Close())  
Application.Run(iqform)

Simplest input validation using Char.IsNumber and Char.IsLetter

The following example demonstrates how to validate a user input by using the Char.IsNumber and Char.IsLetter character manipulation functions:
// Learn more about F# at http://fsharp.net
//specifies the memory location of the class files
//that will be needed in our application
open System.Collections.Generic
open System
open System.Windows.Forms
open System.ComponentModel
open System.Drawing
//creates a font
let ffont=new Font("Verdana", 9.75F,FontStyle.Regular, GraphicsUnit.Point)  
let validateform = new Form(Text="Validate Inputs",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 200),StartPosition=FormStartPosition.CenterScreen)
//creates our controls
let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(190, 170))  
let okbutton=new Button(Text="Ok", Location=new System.Drawing.Point(100, 170)) 
let label1=new Label(Text="Enter a name:",Location=new System.Drawing.Point(0, 10),AutoSize=true)
let nametxtbox=new TextBox(Location=new System.Drawing.Point(120,10),BorderStyle=BorderStyle.FixedSingle)
validateform.Font<-ffont
//adds the controls to our form
validateform.Controls.Add(exitbutton)
validateform.Controls.Add(okbutton)
validateform.Controls.Add(label1)
validateform.Controls.Add(nametxtbox)
//when the oK button is clicked
okbutton.Click.Add(fun ok->
//if the input begins with a letter then
if (Char.IsLetter(Convert.ToChar(nametxtbox.Text.Chars(0)))) then
//prompt that its a valid name
MessageBox.Show("The name you entered is valid ", "Validate Inputs",MessageBoxButtons.OK, MessageBoxIcon.Information)|>ignore
//if the input begins with a number then                         
if (Char.IsNumber(Convert.ToChar(nametxtbox.Text.Chars(0)))) then
//prompt that its an invalid name
MessageBox.Show("You must enter a valid name", "Validate Inputs",MessageBoxButtons.OK, MessageBoxIcon.Information)|>ignore)
//when the exit button is clicked
exitbutton.Click.Add(fun exit->validateform.Close())
//executes our application
Application.Run(validateform)
Click the run icon when done entering these codes in Visual F# code editor window. Try entering any number in the name text box and clicking the ok button. You should see an output similar to the following:

Paint Application in Visual F#

The following example demonstrates how to make a simple Paint-like application in Visual F#:

// Learn more about F# at http://fsharp.net
//specifies the memory location of the class files
//that will be needed in our application
open System.Collections.Generic
open System
open System.Windows.Forms
open System.ComponentModel
open System.Drawing
open System.Drawing.Drawing2D
let drawingform = new Form(Text="Draw Objects",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 250),StartPosition=FormStartPosition.CenterScreen)
//creates our control
let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 200))
let erasebutton=new Button(Text="Erase", Location=new System.Drawing.Point(120, 200))
let colorbutton=new Button(Text="Brush Color", Location=new System.Drawing.Point(40, 200))
drawingform.Controls.Add(exitbutton)
drawingform.Controls.Add(erasebutton)
drawingform.Controls.Add(colorbutton)
//creates a color dialog box
let colordlg=new ColorDialog()
//creates a colorblend object
let mutable color=new ColorBlend()

let gr=drawingform.CreateGraphics()
gr.SmoothingMode<-SmoothingMode.HighQuality
//when the form is loaded, change its color to white
drawingform.Load.Add(fun background->
//set the default brush color to indigo
color.Colors<-[|Color.Indigo|]
                        drawingform.BackColor<-Color.White)

drawingform.MouseMove.Add(fun trail->
//when the mouse button is moved and the left button is clicked

if (trail.Button=System.Windows.Forms.MouseButtons.Left)then
//draw the object assign the color seleted from the color dialog as a brush color
gr.FillRectangle(new SolidBrush(color.Colors.[0]),new Rectangle(trail.X,trail.Y,5,5))) 
//when the erase button is clicked
//erase the object drawn in the form
erasebutton.Click.Add(fun erase->gr.Clear(Color.White)) 
//when the exit button is clicked
//quit the form                                                                                                              
exitbutton.Click.Add(fun quit->drawingform.Close())
//when the brush color button is selected                                                          
colorbutton.Click.Add(fun colors->
//display the Color Dialog box
if colordlg.ShowDialog()=DialogResult.OK then
//store the value selected by the user in our colorblend object
color.Colors<-[|colordlg.Color|])
//executes our application
Application.Run(drawingform)
Click the run icon once you are done entering these codes in the code editor window. You should see the following outputs:

Mouse Trails using Basic shapes

Obsessed with mouse trails? Try the following sample applications:
1. Line Mouse Trail
Code:
// Learn more about F# at http://fsharp.net
//specifies the memory location of the class files
//that will be needed in our application
open System.Collections.Generic
open System
open System.Windows.Forms
open System.ComponentModel
open System.Drawing
let trailform = new Form(Text="Display Mouse Trail",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 250),StartPosition=FormStartPosition.CenterScreen)
//creates our control
let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 200))
let gr=trailform.CreateGraphics()
trailform.Controls.Add(exitbutton)
trailform.MouseMove.Add(fun trail->gr.DrawLine(Pens.Peru,trail.X,trail.Y,trail.X+1,trail.Y+1))                                                                                                                
exitbutton.Click.Add(fun quit->trailform.Close())                                                          
//executes our application
Application.Run(trailform)
Output:

2. Circle Mouse Trail
Code:
// Learn more about F# at http://fsharp.net
//specifies the memory location of the class files
//that will be needed in our application
open System.Collections.Generic
open System
open System.Windows.Forms
open System.ComponentModel
open System.Drawing
let trailform = new Form(Text="Display Mouse Trail",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 250),StartPosition=FormStartPosition.CenterScreen)
//creates our control
let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 200))
let gr=trailform.CreateGraphics()
trailform.Controls.Add(exitbutton)
trailform.MouseMove.Add(fun trail->gr.DrawEllipse(Pens.IndianRed,new Rectangle(trail.X,trail.Y,10,10)))                                                                                                                    
exitbutton.Click.Add(fun quit->trailform.Close())                                                          
//executes our application
Application.Run(trailform)
Output:

3. Rectangle Mouse Trail
Code:
// Learn more about F# at http://fsharp.net
//specifies the memory location of the class files
//that will be needed in our application
open System.Collections.Generic
open System
open System.Windows.Forms
open System.ComponentModel
open System.Drawing
let trailform = new Form(Text="Display Mouse Trail",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 250),StartPosition=FormStartPosition.CenterScreen)
//creates our control
let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 200))
let gr=trailform.CreateGraphics()
trailform.Controls.Add(exitbutton)
trailform.MouseMove.Add(fun trail->gr.DrawRectangle(Pens.Fuchsia,new Rectangle(trail.X,trail.Y,5,5)))                                                                                                                    
exitbutton.Click.Add(fun quit->trailform.Close())                                                          
//executes our application
Application.Run(trailform)
Output:

4. Arc Mouse Trail
Code:
// Learn more about F# at http://fsharp.net
//specifies the memory location of the class files
//that will be needed in our application
open System.Collections.Generic
open System
open System.Windows.Forms
open System.ComponentModel
open System.Drawing
let trailform = new Form(Text="Display Mouse Trail",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 250),StartPosition=FormStartPosition.CenterScreen)
//creates our control
let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 200))
let gr=trailform.CreateGraphics()
trailform.Controls.Add(exitbutton)
trailform.MouseMove.Add(fun trail->gr.DrawArc(Pens.Violet,new Rectangle(trail.X,trail.Y,5,5),180.0f,-180.0f))                                                                                                               
exitbutton.Click.Add(fun quit->trailform.Close())                                                          
//executes our application
Application.Run(trailform)
Output:

5. Filled-Arc/FillPie Mouse Trail
Code:
// Learn more about F# at http://fsharp.net
//specifies the memory location of the class files
//that will be needed in our application
open System.Collections.Generic
open System
open System.Windows.Forms
open System.ComponentModel
open System.Drawing
let trailform = new Form(Text="Display Mouse Trail",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 250),StartPosition=FormStartPosition.CenterScreen)
//creates our control
let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 200))
let gr=trailform.CreateGraphics()
trailform.Controls.Add(exitbutton)
trailform.MouseMove.Add(fun trail->gr.FillPie(Brushes.MidnightBlue,new Rectangle(trail.X,trail.Y,10,10),180.0f,180.0f))                                                                                                               
exitbutton.Click.Add(fun quit->trailform.Close())                                                          
//executes our application
Application.Run(trailform)
Output:

6. Filled Circle Mouse Trail
Code:
// Learn more about F# at http://fsharp.net
//specifies the memory location of the class files
//that will be needed in our application
open System.Collections.Generic
open System
open System.Windows.Forms
open System.ComponentModel
open System.Drawing
let trailform = new Form(Text="Display Mouse Trail",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 250),StartPosition=FormStartPosition.CenterScreen)
//creates our control
let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 200))
let gr=trailform.CreateGraphics()
trailform.Controls.Add(exitbutton)
trailform.MouseMove.Add(fun trail->gr.FillEllipse(Brushes.Tomato,new Rectangle(trail.X,trail.Y,10,10)))                                                                                                               
exitbutton.Click.Add(fun quit->trailform.Close())                                                          
//executes our application
Application.Run(trailform)
Output:

7. Filled Rectangle Mouse Trail
Code:
// Learn more about F# at http://fsharp.net
//specifies the memory location of the class files
//that will be needed in our application
open System.Collections.Generic
open System
open System.Windows.Forms
open System.ComponentModel
open System.Drawing
let trailform = new Form(Text="Display Mouse Trail",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 250),StartPosition=FormStartPosition.CenterScreen)
//creates our control
let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 200))
let gr=trailform.CreateGraphics()
trailform.Controls.Add(exitbutton)
trailform.MouseMove.Add(fun trail->gr.FillRectangle(Brushes.Indigo,new Rectangle(trail.X,trail.Y,20,20)))                                                                                                               
exitbutton.Click.Add(fun quit->trailform.Close())                                                          
//executes our application
Application.Run(trailform)
Output:

Creating a Customized Mouse Pointer

Aside from using pre-defined mouse pointers such as Cursors.Arrow and Cursors.Cross, you can also use customized mouse pointers in Visual F#. Follow these steps for a simple example:

1. Download a cursor creator software such as Axialis CursorWorkShop or Icon Craft.

2. Create a .cur file and name it “pointer.cur”.

3. Start Visual F#>Create a new Project.

4. Enter the following codes:

// Learn more about F# at http://fsharp.net
//specifies the memory location of the class files
//that will be needed in our application
open System.Collections.Generic
open System
open System.Windows.Forms
open System.ComponentModel
open System.Drawing
let mouseform = new Form(Text="Cutom Mouse Pointer",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 250),StartPosition=FormStartPosition.CenterScreen)
//creates our control
let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 200))
let customcur=new System.Windows.Forms.Cursor("pointer.cur")
mouseform.MouseHover.Add(fun cutom->mouseform.Cursor<-customcur) 
mouseform.Controls.Add(exitbutton)                                                                                                
exitbutton.Click.Add(fun quit->mouseform.Close())                                                          
//executes our application
Application.Run(mouseform)

5. Click the Open Folder>bin>debug> then copy and paste pointer.cur.

6. Run your application

Printing an Image Data

To print an image or text, use a PrintDocument control. To following example shows how to print an image data, using a PrintDocument control.

// Learn more about F# at http://fsharp.net
//specifies the memory location of the class files
//that will be needed in our application
open System.Collections.Generic
open System
open System.Windows.Forms
open System.ComponentModel
open System.Drawing
open System.Drawing.Printing

open System.Drawing.Imaging
let imageform = new Form(Text="Print Form",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 250),StartPosition=FormStartPosition.CenterScreen)
//creates our control
let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 200))
let loadbutton=new Button(Text="Load", Location=new System.Drawing.Point(120, 200))
let prnbutton=new Button(Text="Print", Location=new System.Drawing.Point(40, 200))
let pic=new PictureBox(SizeMode=PictureBoxSizeMode.StretchImage,Location=new System.Drawing.Point(20, 20),BorderStyle=BorderStyle.FixedSingle,Size=new System.Drawing.Size(100, 100))
let label=new Label(AutoSize=true,Location=new System.Drawing.Point(0, 120))
let dlg=new OpenFileDialog()
let gr=imageform.CreateGraphics()
let prn=new System.Drawing.Printing.PrintDocument()
imageform .Controls.Add(pic)
imageform.Controls.Add(loadbutton)
imageform.Controls.Add(label)
imageform.Controls.Add(prnbutton)
imageform.Controls.Add(exitbutton)
//sends the data to the printer
prnbutton.Click.Add(fun startprint->prn.Print())

loadbutton.Click.Add(fun load->
//filter dialog result
dlg.Filter <- "JPEG Images (*.jpg,*.jpeg)|*.jpg;*.jpeg|Gif Images (*.gif)|*.gif"
//adds title to your dialog box
                   dlg.Title<-"Select an Image File"
                   if dlg.ShowDialog()=DialogResult.OK then
//creates a bitmap object
//assigns the image selected by the user as its value
                      let bmp=new System.Drawing.Bitmap(dlg.FileName)
                      bmp.RotateFlip(RotateFlipType.RotateNoneFlipNone)
//assigns the loaded image as a picturebox value
                      pic.Image<-bmp
//displays the image url in our label
                      label.Text<-"\t\tFilename:" + Convert.ToString(Convert.ToChar(32))+ (dlg.FileName)) 
//specifies the data to be printed
//in this case our image                      
prn.PrintPage.Add(fun printdata->gr.DrawImage(pic.Image,10,10))
//close the form                                                                                                        
exitbutton.Click.Add(fun quit->imageform.Close())                                         
[]                    
//executes our application
Application.Run(imageform)

Drawing Triangles and Circles

To draw a triangle, use the DrawLine or DrawPolygon method. Here’s an example that uses DrawPolygon method:
// Learn more about F# at http://fsharp.net
// Learn more about F# at http://fsharp.net
//specifies the memory location of the class files
//that will be needed in our application
open System.Collections.Generic
open System
open System.Windows.Forms
open System.ComponentModel
open System.Drawing
let graphicform = new Form(Text="Draw Triangle",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 250),StartPosition=FormStartPosition.CenterScreen)
//creates our control
let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(190, 200))
graphicform.Paint.Add(fun draw->
let array=[|new Point(0,150);new Point(150,10);new Point(300,150)|]
let pen=new Pen(Color.Blue,Width=12.0f)
draw.Graphics.DrawPolygon(pen,array))
graphicform.Controls.Add(exitbutton)
//executes our application
Application.Run(graphicform)
To draw a filled triangle, use the FillPolygon method:
// Learn more about F# at http://fsharp.net
// Learn more about F# at http://fsharp.net
//specifies the memory location of the class files
//that will be needed in our application
open System.Collections.Generic
open System
open System.Windows.Forms
open System.ComponentModel
open System.Drawing
let graphicform = new Form(Text="Draw Triangle",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 250),StartPosition=FormStartPosition.CenterScreen)
//creates our control
let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(190, 200))
graphicform.Paint.Add(fun draw->
let array=[|new Point(0,150);new Point(150,10);new Point(300,150)|]
let brush=new SolidBrush(Color.Blue)
draw.Graphics.FillPolygon(brush,array))
graphicform.Controls.Add(exitbutton)
//executes our application
Application.Run(graphicform)
To draw a circle, use the DrawEllipse method:
// Learn more about F# at http://fsharp.net
// Learn more about F# at http://fsharp.net
//specifies the memory location of the class files
//that will be needed in our application
open System.Collections.Generic
open System
open System.Windows.Forms
open System.ComponentModel
open System.Drawing
let graphicform = new Form(Text="Draw Circle",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 250),StartPosition=FormStartPosition.CenterScreen)
//creates our control
let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(190, 200))
graphicform.Paint.Add(fun draw->

let pen=new Pen(Color.Blue,Width=12.0f)
draw.Graphics.DrawEllipse(pen,0.0f,0.0f,100.0f,100.0f))

graphicform.Controls.Add(exitbutton)
//executes our application
Application.Run(graphicform)
To draw a solid circle, use the FillEllipse method:
// Learn more about F# at http://fsharp.net
// Learn more about F# at http://fsharp.net
//specifies the memory location of the class files
//that will be needed in our application
open System.Collections.Generic
open System
open System.Windows.Forms
open System.ComponentModel
open System.Drawing
let graphicform = new Form(Text="Draw Circle",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 250),StartPosition=FormStartPosition.CenterScreen)
//creates our control
let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(190, 200))
graphicform.Paint.Add(fun draw->

let brush=new SolidBrush(Color.Blue)
draw.Graphics.FillEllipse(brush,0.0f,0.0f,100.0f,100.0f))

graphicform.Controls.Add(exitbutton)
//executes our application
Application.Run(graphicform)

Display the Date or Time from a DateTime Object

There are several ways on how to retrieve the date or time part from a datetime object, here are the few methods that I discover through research and experimentation:

1. Using Substring

Display the time part using Substring:
// 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
let ffont=new Font("Verdana", 14.5F,FontStyle.Regular, GraphicsUnit.Point)
//creates a form
let timerform=new Form(Text="Display Time Part",StartPosition=FormStartPosition.CenterScreen,AutoScaleMode=AutoScaleMode.Font)
let timelabel=new Label(Location=new System.Drawing.Point(20,40),BorderStyle=BorderStyle.FixedSingle,AutoSize=true)

let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 220),AutoSize=true)
//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)
timelabel.Font<-ffont
//change it every 1 min second
timer1.Tick.Add(fun time->
//assigns the current date and time to a variable
let datetime=Convert.ToString(System.DateTime.Now)
//retrieves the value of the datetime variable
//starting from the 11th character
let timepart=datetime.Substring(10)
//display the time
timelabel.Text<-timepart)
                
//adds the exit button to our form
timerform.Controls.Add(timelabel)
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)

Display the time part using the substring function:
// 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
let ffont=new Font("Verdana", 14.5F,FontStyle.Regular, GraphicsUnit.Point)
//creates a form
let dateform=new Form(Text="Display Date Part",StartPosition=FormStartPosition.CenterScreen,AutoScaleMode=AutoScaleMode.Font)
//use the random function to generate random numbers
let datelabel=new Label(Location=new System.Drawing.Point(20,40),BorderStyle=BorderStyle.FixedSingle,AutoSize=true)

let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 220),AutoSize=true)

datelabel.Font<-ffont
dateform.Load.Add(fun time->
//assigns the current date and time to the datetime variable
let datetime=Convert.ToString(System.DateTime.Now)
//retrieves the text from the datetime variable staring from the first
//character to the 11th character
let datepart=datetime.Substring(0,10)
//display the current time
datelabel.Text<-datepart)
                
//adds the exit button to our form
dateform.Controls.Add(datelabel)
dateform.Controls.Add(exitbutton)
//when the exit button is clicked
exitbutton.Click.Add(fun quit->dateform.Close())                   
//execute our application
Application.Run(dateform)


2. Using Remove

Display the time part using Remove:
// 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
let ffont=new Font("Verdana", 14.5F,FontStyle.Regular, GraphicsUnit.Point)
//creates a form
let timerform=new Form(Text="Display Time Part",StartPosition=FormStartPosition.CenterScreen,AutoScaleMode=AutoScaleMode.Font)
let timelabel=new Label(Location=new System.Drawing.Point(20,40),BorderStyle=BorderStyle.FixedSingle,AutoSize=true)

let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 220),AutoSize=true)
//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)
timelabel.Font<-ffont
//change it every 1 min second
timer1.Tick.Add(fun time->
//assigns the current date and time to the datetime variable
let datetime=Convert.ToString(System.DateTime.Now)
//removes the first 11 characters from the datetime variable
let timepart=datetime.Remove(0,10)
//display the current time
timelabel.Text<-timepart)
                
//adds the exit button to our form
timerform.Controls.Add(timelabel)
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)

Display the date part using the Remove function:
// 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
let ffont=new Font("Verdana", 14.5F,FontStyle.Regular, GraphicsUnit.Point)
//creates a form
let dateform=new Form(Text="Display Date Part",StartPosition=FormStartPosition.CenterScreen,AutoScaleMode=AutoScaleMode.Font)
//use the random function to generate random numbers
let datelabel=new Label(Location=new System.Drawing.Point(20,40),BorderStyle=BorderStyle.FixedSingle,AutoSize=true)

let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 220),AutoSize=true)

datelabel.Font<-ffont
dateform.Load.Add(fun time->
//assigns the current date and time to the datetime variable
let datetime=Convert.ToString(System.DateTime.Now)
//removes the text from the datetime variable staring from the 11 character
let datepart=datetime.Remove(10)
//display the current time
datelabel.Text<-datepart)
                
//adds the exit button to our form
dateform.Controls.Add(datelabel)
dateform.Controls.Add(exitbutton)
//when the exit button is clicked
exitbutton.Click.Add(fun quit->dateform.Close())                   
//execute our application
Application.Run(dateform)

SystemSounds in F#

To play a system sound in Visual F#, use the SystemSounds object. For a simple example on using the SystemSounds object, try the following:


// Learn more about F# at http://fsharp.net
//use the f# standard library
open System
//use media classes
open System.Media
//specify the memory location of the classes used in drawing objects
//required to draw the listbox item text
open System.Drawing
//specify the location of the form class
open System.Windows.Forms
//creates a form and assign a "Play System Sounds" caption to it
let soundform=new Form(Text="Play System Sounds",StartPosition=FormStartPosition.CenterScreen,AutoScaleMode=AutoScaleMode.Font)
//creates a label and set its Text to “Count”
let lbl=new Label(Text="System sounds:", Location=new System.Drawing.Point(20,10),AutoSize=true)
//makes a listbox
let soundlistbox=new ListBox(Sorted=true,Location=new System.Drawing.Point(20,30),FormattingEnabled=true)
//adds an item to the listbox when the form is loaded
soundform.Load.Add(fun items->
     //adds the items and ignore the passed index position values
                    soundlistbox.Items.Add("Asterisk")|>ignore
                    soundlistbox.Items.Add("Beep")|>ignore
                    soundlistbox.Items.Add("Exclaimation")|>ignore
                    soundlistbox.Items.Add("Hand")|>ignore
                    soundlistbox.Items.Add("Question")|>ignore)
soundlistbox.Click.Add(fun playsound->
                    if soundlistbox.SelectedIndex=0 then
                        SystemSounds.Asterisk.Play()
                        MessageBox.Show("Asterisk", "System Sounds", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)|>ignore
                    if soundlistbox.SelectedIndex=1 then
                        SystemSounds.Beep.Play()
                        MessageBox.Show("Beep", "System Sounds", MessageBoxButtons.OK)|>ignore
                    if soundlistbox.SelectedIndex=2 then
                        SystemSounds.Exclamation.Play()
                        MessageBox.Show("Exclaimation", "System Sounds", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)|>ignore
                    if soundlistbox.SelectedIndex=3 then
                        SystemSounds.Hand.Play()
                        MessageBox.Show("Hand", "System Sounds", MessageBoxButtons.OK, MessageBoxIcon.Hand)|>ignore
                    if soundlistbox.SelectedIndex=4 then
                       SystemSounds.Question.Play()
                        MessageBox.Show("Question", "System Sounds", MessageBoxButtons.OK, MessageBoxIcon.Question)|>ignore) 
                                           
//displays the label to our form
soundform.Controls.Add(lbl)      
//adds the listbox to our form    
soundform.Controls.Add(soundlistbox)           
soundform.Show()
Application.Run(soundform)

This will generate the following output:

Adding space to a concatenated String

There are several ways to add space to a contanated string in Visual F#:

1.Using the Tab Escape Character

Syntax:
“text1” + “\t” + “textn”

For instance:
Trace.WriteLine("Adding" +”\t”+ “Space”)

This will display “Adding Space” with 5-6 spaces in between in the output window. You can also use the unicode equivalent of tab which is \u0009. For example:
Trace.WriteLine("Adding" +”\u0009”+ “Space”)
2. Typing a space or “ “ between the concatenated strings
Syntax:
“text1” + “ ” + “textn”

For instance:
Trace.WriteLine("Adding" +” ”+ “Space”)
You can also use the unicode equivalent of space which is \u0032. For example:
Trace.WriteLine("Adding" +”\u0032”+ “Space”)
3. Using the Convert.ToChar() string manipulation function
Convert.ToChar converts a specified key code to character.
The key code for tab is 9 while Spacebar has 32.

Syntax:
Convert.ToChar(key code)
Examples:
//backspace key
Trace.WriteLine(Convert.ToString(Convert.ToChar(8)))
//enter key
Trace.WriteLine(Convert.ToString(Convert.ToChar(13)))
//adds space to a concatenated string
Trace.WriteLine(“Adding” + Convert.ToString(Convert.ToChar(32)) + “Space” )

For a simple example of application that adds space to a concatenated string:

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
//specifies the namespace memory location of the classes that
//will be used in our application
open System
open System.Diagnostics
open System.Windows.Forms
open System.Drawing
//creates our form
let myform= new Form(Text="Adding Space")
//creates our controls  
let label1=new Label(Text="Firstname:",Location=new System.Drawing.Point(0, 10),AutoSize=true)
let label2=new Label(Text="Lastname:",Location=new System.Drawing.Point(0, 50),AutoSize=true)
let fnametextbox=new TextBox(Location=new System.Drawing.Point(100,10),BorderStyle=BorderStyle.FixedSingle)
let lnametextbox=new TextBox(Location=new System.Drawing.Point(100,50),BorderStyle=BorderStyle.FixedSingle)
let okbutton=new Button(Text="Ok", Location=new System.Drawing.Point(120, 170))
let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 170))
myform.Controls.Add(label1)
myform.Controls.Add(label2
myform.Controls.Add(fnametextbox)
myform.Controls.Add(lnametextbox)
myform.Controls.Add(okbutton)
myform.Controls.Add(exitbutton)
myform.Click.Add(fun space->
//display our text in the ouput window
Trace.WriteLine("Adding Spaces")
Trace.WriteLine(label1.Text + "\u0009" + fnametextbox.Text)
Trace.WriteLine(label2.Text + "\u0009" + lnametextbox.Text))

//execute our application
myform.Show()
Application.Run(myform)

Gradient and Textured Form in Visual F#

To create a gradient form in Visual F#, simply use a gradient brush and use that brush to draw a rectangle that will cover the whole form area. To create a LinearGradientBrush, use the following syntax:
let newbrush=new LinearGradientBrush(brushpoint,color1,color2,strokeangle)
For instance:
let newbrush=new LinearGradientBrush(rect,Color.Green,Color.YellowGreen,45.0F)
Follow these steps to create a gradient form using the LinearGradientBrush drawing method:

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
//specifies the namespace memory location of the classes that
//will be used in our application
open System
open System.Windows.Forms
open System.Drawing
open System.Drawing.Drawing2D
//creates our form
let myform= new Form(Text="Add Gradient Background")
//create a rectangle
//change its upper left x and y coordinates to 0,0
//sets it width and height to the width and height of the form
let rect=new Rectangle(0,0,myform.Width,myform.Height)
//creates a gradient brush
let newbrush=new LinearGradientBrush(rect,Color.Green,Color.YellowGreen,45.0F)
//paints our form with a solid and filled rectangle
myform.Paint.Add(fun fillrect->fillrect.Graphics.FillRectangle(newbrush,rect)) 
//executes our application
myform.Show()
Application.Run(myform)

This will display the following output:



To create a textured form, use a TextureBrush to draw a rectangle that will cover the whole form area then display that rectangle on your form.

For instance:
// Learn more about F# at http://fsharp.net
//specifies the namespace memory location of the classes that
//will be used in our application
open System
open System.Windows.Forms
open System.Drawing
open System.Drawing.Drawing2D

//creates our form
let myform= new Form(Text="Add Textured Background")
//draws a rectangle with the same width and height as our form
let drawrect=new Rectangle(0,0,myform.Width,myform.Height)
//creates a texturedbrush using a windows default image
//tile the image Vertically and Horizontally
let newbrush=new TextureBrush(new Bitmap("C:\Windows\Zapotec.bmp"),WrapMode=WrapMode.TileFlipXY)
//applies the brush in drawing our rectangle
myform.Paint.Add(fun fillrect->fillrect.Graphics.FillRectangle(newbrush, drawrect)) 
//executes our application
myform.Show()
Application.Run(myform)

Add navigational buttons to a database application without using a BindingNavigator

On my previous post, we were able to add a navigational button to our application by using a BindingNavigator, today, we will do everything manually. To add a navigational button by hand, all you need to do is to bind your controls using this method and increment or decrement the Row index number to navigate around your records. This method is slightly similar to the methods used by most developers in adding navigational buttons to VB.net database applications.

For the sake of example, follow these steps(I assume here that you have already created a database file named “dbEmployee” and a table named “tblEmployee”):

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 and System.Data 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
//specifies the memory location of the class files
//that will be needed in our application
open System
open System.Windows.Forms
open System.Data
open System.Drawing
open System.Data.OleDb
//creates a font
let ffont=new Font("Verdana", 9.75F,FontStyle.Regular, GraphicsUnit.Point)  
//creates a connection object
let oleconn = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;
  Data Source=C:\Documents and Settings\Administrator\My Documents\dbEmployee.mdb")
 //creates an OleDbDataAdapter
let dataadpter = new System.Data.OleDb.OleDbDataAdapter("Select * from tblEmployee", oleconn)
let deletecommand=new System.Data.OleDb.OleDbCommand()

//generates a dataset
let dataset11 = new DataSet()
//fills the dataset with recod values
dataadpter.Fill(dataset11,"tblEmployee")|>ignore
//creates a form
let dataform = new Form(Text="Add Navigational Buttons Manually",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 200),StartPosition=FormStartPosition.CenterScreen)
//creates our controls
let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 170))  
let label1=new Label(Text="Employee number:",Location=new System.Drawing.Point(0, 10),AutoSize=true)
let label2=new Label(Text="Firstname:",Location=new System.Drawing.Point(0, 50),AutoSize=true)
let label3=new Label(Text="Lastname:",Location=new System.Drawing.Point(0,100),AutoSize=true)
let emplabel=new Label(Location=new System.Drawing.Point(140,10),BorderStyle=BorderStyle.FixedSingle)
let fnamelabel=new Label(Location=new System.Drawing.Point(100,50),BorderStyle=BorderStyle.FixedSingle)
let lnamelabel=new Label(Location=new System.Drawing.Point(100,100),BorderStyle=BorderStyle.FixedSingle)
let topbutton=new Button(Text="Top", Location=new System.Drawing.Point(40, 170))
let bottombutton=new Button(Text="Bottom", Location=new System.Drawing.Point(120, 170))
//assings the font to our form
dataform.Font<-ffont
//adds the controls to our form
dataform.Controls.Add(exitbutton)
dataform.Controls.Add(label1)
dataform.Controls.Add(label2)
dataform.Controls.Add(label3)
dataform.Controls.Add(emplabel)
dataform.Controls.Add(fnamelabel)
dataform.Controls.Add(lnamelabel)
dataform.Controls.Add(topbutton)
dataform.Controls.Add(bottombutton)

//binds the fieldnames to our label
emplabel.Text<-Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(0).Item(0))
fnamelabel.Text<-Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(0).Item(1))
lnamelabel.Text<-Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(0).Item(2))

//when the topbutton is clicked
//assigns 0 rowindexnumber value causing the 
//first record to be displayed
topbutton.Click.Add(fun top->
emplabel.Text<-Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(0).Item(0))
fnamelabel.Text<-Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(0).Item(1))
lnamelabel.Text<-Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(0).Item(2)))

//when the bottombutton is clicked
//assign the index number of the last row as a rowindexnumer
//since we only have two records on our table
//so the index number of the last row is understood to be 1
//when manipulating large number of records, i suggest using
//dataset11.Tables.["tblEmployee"].Rows.Count() to
//automatically count the number of records

bottombutton.Click.Add(fun bottom->
emplabel.Text<-Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(1).Item(0))
fnamelabel.Text<-Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(1).Item(1))
lnamelabel.Text<-Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(1).Item(2)))

//when the exit button is clicked
exitbutton.Click.Add(fun exit->
//close the form and dataconnection
                    dataform.Close()
                    oleconn.Close())

//executes our application
dataform.Show()
Application.Run(dataform)

5. This will display the following output:



6. Simple...right?

Yet another way of binding a control to a field name in Visual F#

On my last post, I’ve shown you how to bind a record value to a control using the DataBindings method. Another way of binding a control to a fieldname is by using Text property of a control and assigning the dataset collection properties as its value:

Syntax:

controlobjvariable.Text<- (datasetname.Tables.["tablename"].Rows.Item(rowindexnumber).Item(columnindexnumber))
For instance:
emplabel.Text<-Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(0).Item(0))
The rowindexnumber of the first record on your table is 0, the second record is 1 and so on. Same goes with the columnindexnumber. For a simple example of application that uses the binding method above, follow these steps(I assume here that you have already created a database file named “dbEmployee” and a table named “tblEmployee”):
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 and System.Data 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
//specifies the memory location of the class files
//that will be needed in our application
open System
open System.Windows.Forms
open System.Data
open System.Drawing
open System.Data.OleDb
//creates a font
let ffont=new Font("Verdana", 9.75F,FontStyle.Regular, GraphicsUnit.Point)  
//creates a connection object
let oleconn = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;
  Data Source=C:\Documents and Settings\Administrator\My Documents\dbEmployee.mdb")
 //creates an OleDbDataAdapter
let dataadpter = new System.Data.OleDb.OleDbDataAdapter("Select * from tblEmployee", oleconn)
let deletecommand=new System.Data.OleDb.OleDbCommand()

//generates a dataset
let dataset11 = new DataSet()
//fills the dataset with recod values
dataadpter.Fill(dataset11,"tblEmployee")|>ignore
//creates a form
let dataform = new Form(Text="Bind Form Control Part 2",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 200),StartPosition=FormStartPosition.CenterScreen)
//creates our controls
let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(190, 170))  
let label1=new Label(Text="Employee number:",Location=new System.Drawing.Point(0, 10),AutoSize=true)
let label2=new Label(Text="Firstname:",Location=new System.Drawing.Point(0, 50),AutoSize=true)
let label3=new Label(Text="Lastname:",Location=new System.Drawing.Point(0,100),AutoSize=true)
let emplabel=new Label(Location=new System.Drawing.Point(140,10),BorderStyle=BorderStyle.FixedSingle)
let fnamelabel=new Label(Location=new System.Drawing.Point(100,50),BorderStyle=BorderStyle.FixedSingle)
let lnamelabel=new Label(Location=new System.Drawing.Point(100,100),BorderStyle=BorderStyle.FixedSingle)
//assings the font to our form
dataform.Font<-ffont
//adds the controls to our form
dataform.Controls.Add(exitbutton)
dataform.Controls.Add(label1)
dataform.Controls.Add(label2)
dataform.Controls.Add(label3)
dataform.Controls.Add(emplabel)
dataform.Controls.Add(fnamelabel)
dataform.Controls.Add(lnamelabel)

//binds the fieldnames to our label
emplabel.Text<-Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(0).Item(0))
fnamelabel.Text<-Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(0).Item(1))
lnamelabel.Text<-Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(0).Item(2))

//when the exit button is clicked
exitbutton.Click.Add(fun exit->
//close the form and dataconnection
                    dataform.Close()
                    oleconn.Close())

//executes our application
dataform.Show()
Application.Run(dataform)
5. This will display the following output:

Manipulating an Image Data in Visual F#

To manipulate an image data, simply add an oleobject fieldname on your table and insert a bitmap image to it. To display the image on your form, use a picturebox control then bind your oleobject fieldname to it using the following syntax:
Pictureboxobjname.DataBindings.Add(new Binding(pictureboxproperty,datasource,fieldname))
For instance:
appico.DataBindings.Add(new Binding("Image",bindingsource,"oleapplogo",true))
The last boolean parameter enables the control formatting. We also use the Image property instead of the usual Text for the fact that it is the property used to display an image on your form.

Before proceding to the steps below, I want you to make an Ms-Access 2003 or 2007 database file named “dbApplication”. Create a table inside it and name it “tblApplication”. Use the following specifications:



Chrappname Text Handles the application name
Oleapplogo OLE Object Handles the application ico

After creating your table, you can add appropriate values to it for instance:




chrappname oleapplogo
PHP Bitmap Image
Apache Bitmap Image

Bitmap Image refers the the Bitmap Object that you have inserted using the Paste From Ms-Paint command.

After creating the table and adding appropriate values to it.We are now ready for our sample application. Just 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 and System.Data 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
//specifies the memory location of the class files
//that will be needed in our application
open System
open System.Windows.Forms
open System.Data
open System.Drawing
//creates a font
let ffont=new Font("Verdana", 9.75F,FontStyle.Regular, GraphicsUnit.Point)  
//creates a connection object
let oleconn = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;
  Data Source=C:\Documents and Settings\station 2\My Documents\dbApplication.mdb")
 //creates an OleDbDataAdapter
let dataadpter = new System.Data.OleDb.OleDbDataAdapter("Select * from tblApplication", oleconn)
//generates a dataset
let dataset11 = new DataSet()
//fills the dataset with recod values
dataadpter.Fill(dataset11,"tblApplication")|>ignore
//creates a form
let dataform = new Form(Text="Manipulate Image Data",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 200),StartPosition=FormStartPosition.CenterScreen)
//creates our controls  
let label1=new Label(Text="App. name:",Location=new System.Drawing.Point(0, 10),AutoSize=true)
let label2=new Label(Text="Icon:",Location=new System.Drawing.Point(0, 50),AutoSize=true)
let appnamelabel=new Label(Location=new System.Drawing.Point(140,10),BorderStyle=BorderStyle.FixedSingle)
let appico=new PictureBox(SizeMode=PictureBoxSizeMode.StretchImage,Location=new System.Drawing.Point(140,50))

let bindingsource=new BindingSource()
//creates a binding navigator
//this will allow us to add navigational buttons to our data grid
let bindingnav=new BindingNavigator(Dock=DockStyle.None,Location=new System.Drawing.Point(100, 170))
//creates a toolstrip buttons for our binding navigator
let movefirst=new ToolStripButton(Text="Top")
let moveprev=new ToolStripButton(Text="Prev")
let movenext=new ToolStripButton(Text="Next")
let movelast=new ToolStripButton(Text="Bottom")
let exitbutton=new ToolStripButton(Text="Exit")
//adds the toolstripbuttons to our binding navigator
bindingnav.Items.Add(movefirst)|>ignore
bindingnav.Items.Add(moveprev)|>ignore
bindingnav.Items.Add(movenext)|>ignore
bindingnav.Items.Add(movelast)|>ignore
bindingnav.Items.Add(exitbutton)|>ignore
//adds a function to each buttons
bindingnav.MoveFirstItem<-movefirst
bindingnav.MoveNextItem<-movenext
bindingnav.MovePreviousItem<-moveprev
bindingnav.MoveLastItem<-movelast
exitbutton.Click.Add(fun exit->
//close the form and dataconnection
                    dataform.Close()
                    oleconn.Close())
//assigns the dataset name as a bindingsource datasource
bindingsource.DataSource<-dataset11
//assigns our table as a binding source datamember
bindingsource.DataMember<-"tblApplication"
//assigns the bindingsource name as a binding navigators
//bindingsource value
bindingnav.BindingSource<-bindingsource
//opens the connection
oleconn.Open()
//assings the font to our form
dataform.Font<-ffont
//adds the controls to our form
dataform.Controls.Add(label1)
dataform.Controls.Add(label2)
dataform.Controls.Add(appnamelabel)
dataform.Controls.Add(appico)

dataform.Controls.Add(bindingnav)
//binds the fieldnames to our label
appnamelabel.DataBindings.Add(new Binding("Text",bindingsource,"chrappname"))
appico.DataBindings.Add(new Binding("Image",bindingsource,"oleapplogo",true))
//executes our application
dataform.Show()
Application.Run(dataform)
5. Click the run icon to execute your application. You should now see an output similar to the following screen shot: 6. Here’s another version of the code above without BindingSource and BindingNavigator.
// Learn more about F# at http://fsharp.net
//specifies the memory location of the class files
//that will be needed in our application
open System
open System.Windows.Forms
open System.Data
open System.Drawing
//creates a font
let ffont=new Font("Verdana", 9.75F,FontStyle.Regular, GraphicsUnit.Point)  
//creates a connection object
let oleconn = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;
  Data Source=C:\Documents and Settings\station 2\My Documents\dbApplication.mdb")
 //creates an OleDbDataAdapter
let dataadpter = new System.Data.OleDb.OleDbDataAdapter("Select * from tblApplication", oleconn)
//generates a dataset
let dataset11 = new DataSet()
//fills the dataset with recod values
dataadpter.Fill(dataset11,"tblApplication")|>ignore
//creates a form
let dataform = new Form(Text="Manipulate Image Data",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 200),StartPosition=FormStartPosition.CenterScreen)
//creates our controls  
let label1=new Label(Text="App. name:",Location=new System.Drawing.Point(0, 10),AutoSize=true)
let label2=new Label(Text="Icon:",Location=new System.Drawing.Point(0, 50),AutoSize=true)
let appnamelabel=new Label(Location=new System.Drawing.Point(140,10),BorderStyle=BorderStyle.FixedSingle)
let appico=new PictureBox(SizeMode=PictureBoxSizeMode.StretchImage,Location=new System.Drawing.Point(140,50))
//opens the connection
oleconn.Open()
//assings the font to our form
dataform.Font<-ffont
//adds the controls to our form
dataform.Controls.Add(label1)
dataform.Controls.Add(label2)
dataform.Controls.Add(appnamelabel)
dataform.Controls.Add(appico)
//binds the fieldnames to our label
appnamelabel.DataBindings.Add(new Binding("Text",dataset11,"tblApplication.chrappname"))
appico.DataBindings.Add(new Binding("Image",dataset11,"tblApplication.oleapplogo",true))
//executes our application
dataform.Show()
Application.Run(dataform)
For more sketchy tutorials on Visual F# visit Microsoft F# Developer Center.

Adding navigational Buttons to your database application

The fastest way to add navigational buttons to your database application is to use a BindingNavigator. If you are not yet familiar with Binding Navigator, I suggest reading this post first before proceeding to the steps below:

Before the Database Connection and Binding process I want you to make an Ms-Access database file named “dbEmployee” containing a table named “tblEmployee”. Use the following specifications:

Field NameData Type Description
chrempno text Handles employee id
chrfnametext Handles employee’s name
chrlname text Holds employee’s last name


After designing the structure of your table, you can enter appropriate values for each field. For instance:

chrempnochrfnameChrlname
1John Doe
2Jean Doe


Now that we are done creating a table, we can now link to it by using OleDbDataAdapter in Visual F#:


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 and System.Data 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
//specifies the memory location of the class files
//that will be needed in our application
open System
open System.Windows.Forms
open System.Data
open System.Drawing
//creates a font
let ffont=new Font("Verdana", 9.75F,FontStyle.Regular, GraphicsUnit.Point)  
//creates a connection object
let oleconn = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;
  Data Source=C:\Documents and Settings\station 2\My Documents\dbEmployee.mdb")
 //creates an OleDbDataAdapter
let dataadpter = new System.Data.OleDb.OleDbDataAdapter("Select * from tblEmployee", oleconn)
//generates a dataset
let dataset11 = new DataSet()
//fills the dataset with recod values
dataadpter.Fill(dataset11,"tblEmployee")|>ignore
//creates a form
let dataform = new Form(Text="Add Navigational Buttons",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 200),StartPosition=FormStartPosition.CenterScreen)
//creates our controls  
let label1=new Label(Text="Employee number:",Location=new System.Drawing.Point(0, 10),AutoSize=true)
let label2=new Label(Text="Firstname:",Location=new System.Drawing.Point(0, 50),AutoSize=true)
let label3=new Label(Text="Lastname:",Location=new System.Drawing.Point(0,100),AutoSize=true)
let emplabel=new Label(Location=new System.Drawing.Point(140,10),BorderStyle=BorderStyle.FixedSingle)
let fnamelabel=new Label(Location=new System.Drawing.Point(100,50),BorderStyle=BorderStyle.FixedSingle)
let lnamelabel=new Label(Location=new System.Drawing.Point(100,100),BorderStyle=BorderStyle.FixedSingle)
let bindingsource=new BindingSource()
//creates a binding navigator
//this will allow us to add navigational buttons to our data grid
let bindingnav=new BindingNavigator(Dock=DockStyle.None,Location=new System.Drawing.Point(100, 170))
//creates a toolstrip buttons for our binding navigator
let movefirst=new ToolStripButton(Text="Top")
let moveprev=new ToolStripButton(Text="Prev")
let movenext=new ToolStripButton(Text="Next")
let movelast=new ToolStripButton(Text="Bottom")
let exitbutton=new ToolStripButton(Text="Exit")
//adds the toolstripbuttons to our binding navigator
bindingnav.Items.Add(movefirst)|>ignore
bindingnav.Items.Add(moveprev)|>ignore
bindingnav.Items.Add(movenext)|>ignore
bindingnav.Items.Add(movelast)|>ignore
bindingnav.Items.Add(exitbutton)|>ignore
//adds a function to each buttons
bindingnav.MoveFirstItem<-movefirst
bindingnav.MoveNextItem<-movenext
bindingnav.MovePreviousItem<-moveprev
bindingnav.MoveLastItem<-movelast
exitbutton.Click.Add(fun exit->
//close the form and dataconnection
                    dataform.Close()
                    oleconn.Close())
//assigns the dataset name as a bindingsource datasource
bindingsource.DataSource<-dataset11
//assigns our table as a binding source datamember
bindingsource.DataMember<-"tblEmployee"
//assigns the bindingsource name as a binding navigators
//bindingsource value
bindingnav.BindingSource<-bindingsource
//opens the connection
oleconn.Open()
//assings the font to our form
dataform.Font<-ffont
//adds the controls to our form
dataform.Controls.Add(label1)
dataform.Controls.Add(label2)
dataform.Controls.Add(label3)
dataform.Controls.Add(emplabel)
dataform.Controls.Add(fnamelabel)
dataform.Controls.Add(lnamelabel)
dataform.Controls.Add(bindingnav)
//binds the fieldnames to our label
emplabel.DataBindings.Add(new Binding("Text",bindingsource,"chrempno"))
fnamelabel.DataBindings.Add(new Binding("Text",bindingsource,"chrfname"))
lnamelabel.DataBindings.Add(new Binding("Text",bindingsource,"chrlname"))
//executes our application
dataform.Show()
Application.Run(dataform)
5. Click the run icon to execute your application. You should now see an output similar to the following screen shot: For more sketchy tutorials on Visual F# visit Microsoft F# Developer Center.