I’m currently working my way through “Real World Functional Programming”. I am trying to get example 1.12 working, a “hello world” program using windows forms. This is the code:-
open System.Drawing;;
open System.Windows.Forms;;
type HelloWindow() =
let frm = new Form(Width = 400, Height = 140)
let fnt = new Font("Times New Roman", 28.0f)
let lbl = new Label(Dock = DockStyle.Fill, Font = fnt,
TextAlign = ContentAlignment.MiddleCenter)
do frm.Controls.Add(lbl)
member x.SayHello(name) =
let msg = "Hello" + name + "!"
lbl.Text <- msg
member x.Run() =
Application.Run(frm);;
let hello = new HelloWindow();;
hello.SayHello("you");;
hello.Run();;
Unfortunately, this throws an error – “Starting a second message loop on a single thread is not a valid operation.” So obviously there is a window opening and not terminating and that is confusing the program. I can’t see how to fix the error, can anyone help me out?
I have also tried inputting the final code block as:-
let hello = new HelloWindow()
hello.SayHello("you")
hello.Run();;
But that does not help. The code runs fine but produces no result with the last line commented out.
The example was meant to compile and run as a Windows Form application. If you would like to run it in F# Interactive, you have to use
frm.Show()instead ofApplication.Run(frm).You could make the example work both in F# Interactive and in compiled projects using compiler directives: