Skip to content

Instantly share code, notes, and snippets.

@maestrow
Last active April 16, 2023 18:04
Show Gist options
  • Save maestrow/a23f77959c3774585afd459a67dd6af6 to your computer and use it in GitHub Desktop.
Save maestrow/a23f77959c3774585afd459a67dd6af6 to your computer and use it in GitHub Desktop.
WinForms with F#

How to use F# in WinForms application?

Visual Studio Community Edition 2017 has F# project template, but it hasn't forms desigler for it, designer exists only in C# WinForms project template. To get round this inconvenience, we can create two projects: C# WinForms (only to use VS forms designer) and F#, where we put all logic. See below for more detailed instructions and animated gif.

Create solution with C# and F# projects in Visual Studio

  • Create New F# Library Project.
  • Create New C# Windows Forms Project. I prefer add ".UiDesign" suffix, because this project exists only to use VS Forms Designer.
  • For C# project change Output type property to Class library, for F# - to Windows Application.
  • Add references to F# project:
    • System.Drawing
    • System.Windows.Forms
    • C# project (MyProject.UiDesign)
  • Add button and label controls to your form (C# proj).
  • Go to Form1.Designer.cs and replace all private modifiers to public (or protected).
  • Build C# project.
  • Delete all *.fs* files from your F# project and add StartupForm.fs and Main.fs (in that order. Note, that order of files in F# project does matter and you can change it in solution explorer). Get content for that files from below.

StartupForm.fs

namespace WinformsFs
open WinformsFs.UiDesign

type StartupForm() as this = 
    inherit Form1()
    do
        this.button1.Click.Add <| fun _ -> this.label1.Text <- "Hello"

Main.fs

module WinformsFs.Main

open System
open System.Windows.Forms

[<EntryPoint; STAThread>]
let main argv =
    Application.EnableVisualStyles()
    Application.SetCompatibleTextRenderingDefault(false)
    use form = new StartupForm()
    Application.Run(form)    
    0 // return an integer exit code
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment