Embedded WebBrowser

Parsing and displaying HTML and Web content is an overwhelmingly complex issue. If you want to just display rich text inside your application (e.g. documentation) you usually need to rely on an external parser library. Luckily, Winforms provides an embedded web browser through System.Windows.Forms.WebBrowser. The Mono implementation relies on the Mozilla Gecko engine.

> open System.Windows.Forms;;
> let f = new Form();;

val f : Form = System.Windows.Forms.Form, Text: 

> f.Visible <- true;;
val it : unit = ()
> let b = new WebBrowser();;

val b : WebBrowser = System.Windows.Forms.WebBrowser

> f.Controls.Add(b);;
val it : unit = ()
> b.Dock <- DockStyle.Fill;;
val it : unit = ()
> f.Width <- 1024;;
val it : unit = ()
> f.Height <- 768;;
val it : unit = ()
> b.Url <- System.Uri("http://www.2sharp4u.wordpress.com");;
val it : unit = ()

This should result in the following screen in your application.

Next we create a full scale web browser for our own purpose.

open System
open System.Drawing
open System.Windows.Forms

let form = new Form(Visible=true, Text="Web Browser")
let container = new TableLayoutPanel(ColumnCount=2, RowCount=3)
let label = new Label(Text="Address:")
let address = new TextBox()
let toolbar = new ToolStrip()
let content = new WebBrowser()
let back = new ToolStripButton("BACK")
let forward = new ToolStripButton("FORWARD")

label.TextAlign <- ContentAlignment.MiddleRight

form.Width <- 1024
form.Height <- 768

container.Dock <- DockStyle.Fill
address.Dock <- DockStyle.Fill
content.Dock <- DockStyle.Fill

toolbar.Items.Add(back) |> ignore
toolbar.Items.Add(forward) |> ignore

form.Controls.Add(container)
container.Controls.Add(label, 0, 0)
container.Controls.Add(address, 1, 0)
container.Controls.Add(toolbar, 0, 1)
container.Controls.Add(content, 0, 2)

container.SetColumnSpan(toolbar, 2)
container.SetColumnSpan(content, 2)

content.Refresh()

back.Click.Add(fun _ -> content.GoBack() |> ignore)
forward.Click.Add(fun _ -> content.GoForward() |> ignore)

address.KeyDown.Add(fun e -> if e.KeyCode = Keys.Enter then
 try content.Url <- System.Uri(address.Text)
 with _ -> ())

form.Show()
#if COMPILED
[<STAThread()>]
Application.Run(form)
#endif

After compiling and launching the application you should get the following screen:

Advertisements
This entry was posted in GUI, Web. Bookmark the permalink.

One Response to Embedded WebBrowser

  1. Pingback: Rick Minerich's Development Wonderland : F# Discoveries This Week 10/11/2010

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s