matlabdbuser
matlabdbuser

Reputation: 838

f#: windows form in a compiled program

To visualize data from F# interactive console, I can do the following:

open System.Windows.Forms
let  testgrid (x) =    
          let form = new Form(Visible = true)    
          let data = new DataGridView(Dock = DockStyle.Fill)    
          form.Controls.Add(data)    
          data.DataSource <- x

testgrid [|(1,1);(2,2)|]

But if put the above in a compiled F# program and call testgrid [|(1,1);(2,2)|] within the program, I only got a freezing window without data. what need to be done to make this testgrid works for complied F# program? EDIT: with ildjarn's answer and some search, is the following code ok? Any pitfalls?

let testgrid x =
    let makeForm() = 
        use form = new Form()
        new DataGridView(Dock = DockStyle.Fill, DataSource = x) |> form.Controls.Add
        Application.Run form
    let thread = new System.Threading.Thread(makeForm)
    thread.SetApartmentState(Threading.ApartmentState.STA)
    thread.Start()

Upvotes: 3

Views: 450

Answers (1)

ildjarn
ildjarn

Reputation: 62975

You need a message pump; FSI already has one, which is why your code works from the FSI console, but a standalone program won't have one unless you make one:

open System
open System.Windows.Forms

let testgrid x =
    use form = new Form()
    new DataGridView(Dock = DockStyle.Fill, DataSource = x) |> form.Controls.Add
    Application.Run form

[<STAThread>]
do testgrid [|(1,1);(2,2)|]

Upvotes: 3

Related Questions