Monday, February 2, 2009

F# – User Interface

F# can access .NET assemblies, so Windows Forms is the UI library for F#. The following code reads microsoft.com and displays the HTML code in a TextBox.

#light
open System.Windows.Forms
open System.IO
open System.Net

let form = new Form(Visible=false,Text="Hello F#")

let result = new TextBox(Multiline=true,Dock=DockStyle.Fill, Text="")
form.Controls.Add(result)

let getHtml (url: string) =
    let req = System.Net.WebRequest.Create(url)
    let resp = req.GetResponse()
    printfn "Connected"
    let stream = resp.GetResponseStream()
    let reader = new StreamReader(stream)
    let html = reader.ReadToEnd()
    printfn "Response read"
    resp.Close()
    html
    
printfn "Connecting..."
let microsoft = getHtml("http://www.microsoft.com")
result.Text <- microsoft

form.Visible <- true
Application.Run(form)
Connecting...
Connected
Response read

As you can see, Windows Forms knowledge is a requirement for F# UI development. Personally I don’t think UI elements should be developed in F#, C# has much better IDE designer support so far (F# don’t have designers).

No comments:

Post a Comment