Showing posts with label Visual F#. Show all posts
Showing posts with label Visual F#. Show all posts

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)