Introduction
Today I am going to explain how to change the color of a Form in a Button click event in a F# Windows Forms application using Visual Studio 2010. This is showing how to create a form and how to register an event handler. When you click the Button the form will change its background color. If you want to build a Windows Forms application in F# you need to install the F# Windows Application (winform) template which you can download from my previous article.
The code of the winform application contains a different section as we are discussing it in Points.
Open
The first four lines of F# program is for import declarations as we usually import "Open System", "Open System.Drawing", "Open System.Windows.Forms" and "Open System.Windows.Forms.Design". The purpose of the Import declarations in F# is that additional namespaces can be provide to F# compiler to search for Type definition.
Example
open System
open System.Drawing
open System.Windows.Forms
open System.Windows.Forms.Design
Let
Let is a Keyword in F#. The Let keyword helps us to bind a name to functions. Here indentation is important, because the let keyword tells the compiler that indented lines belongs to which function. If we use let inside the function this will restrict the scope of that particular association. In the following you can see that here we bind the "Button" with a function that defines the properties of Button.
Example
let form = new Form(Text = "Introducing Button!")
let btn = new Button(Text = "Click to Change Color")
Do
Do is also a Keyword in F#. The code of F# can also run without a Do keyword. This keyword is optional. The Do keyword generally instructs the execution of code.
Example
do btn.Size <- new System.Drawing.Size(130,30)
do btn.Location <- new Drawing.Point(90,100)
(<-)
This symbol is used for the operator named assignment through which we can assign a value to mutable variables. We can not change the value of a variable once it is assigned unless they are defined as mutable variables.
Example
btn.Click.Add(fun _ ->
let rnd = new Random()
let r, g, b = rnd.Next(256), rnd.Next(256), rnd.Next(256)
form.BackColor <- Color.FromArgb(r, g, b) )




Join the conversation! Your thoughts help the community grow.