Creating an F# WinForms application

I wanted to mess around with the FSharp.Charting library and needed to create an F# WinForms application to use it.

It’s pretty simple but there’s no template by default in Visual Studio (well not in 2013).

So here the steps to create a WinForms F# application

  • Create a new Project and select F# Application
  • This will be a console application, so next select the project properties and change the Application | Output type from Console Application to Windows Application
  • Add a reference to System.Windows.Forms
  • Change your main function to look like the following
    open System
    open System.Windows.Forms
    
    [<EntryPoint>]
    [<STAThread>]
    let main argv = 
    
        Application.EnableVisualStyles()
        Application.SetCompatibleTextRenderingDefault false
    
        use form = new Form()
    
        Application.Run(form);
    
        0 
    

Obviously this example shows us creating an empty Form. By default F# (at least in Visual Studio 2013) doesn’t include WinForm design surfaces or the likes. So it’s probably best to design your forms in a C# library and reference from your F# applications. Or, alternatively, you can hand code your WinForms.

A quick example of using FSharp.Charting

This is not mean’t to be anything other than a quick example, but as I wanted to get a F# WinForms application specifically to try out some FSharp.Charting, here’s the steps…

  • Using NuGet add a reference to FSharp.Charting to your project (developed above)
  • Add open FSharp.Charting to your Program.fs file
  • I’m going to simple use some code from the FSharp.Charting github samples, so first we need to add a reference to System.Drawing
  • Add a reference to System.Windows.Forms.DataVisualization
  • Finally change the Application.Run method to look like the following
    Application.Run (Chart.Line([ for x in 0 .. 10 -> x, x*x ]).ShowChart())
    

Now your code should look like the following

open System
open System.Windows.Forms
open FSharp.Charting

[<EntryPoint>]
[<STAThread>]
let main argv = 

    Application.EnableVisualStyles()
    Application.SetCompatibleTextRenderingDefault false

    Application.Run (Chart.Line([ for x in 0 .. 10 -> x, x*x ]).ShowChart())

    0

and this should (when run) display a line chart.