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.