F# VS2019 Windows Forms

Viewed 790

I'm learning F# and I'm just trying to build Animate a pendulum program. Here's the code: https://rosettacode.org/wiki/Animate_a_pendulum#F.23

As far as I understand, VS 2019 doesn't support WinForms in F# (maybe, I'm wrong), so I have error messages, trying to copy/paste that code:

enter image description here

What should I do?
Thanks a lot !

2 Answers

If you're looking to use Winforms on .NET core, you'll need to do the following in your project:

  1. Open the project file (double-click on the node in Visual Studio)
  2. Change the Sdk to Microsoft.NET.Sdk.WindowsDesktop
  3. Ensure you have this OutputType: <OutputType>WinExe</OutputType>
  4. Add the following property to the top-level PropertyGroup: <UseWindowsForms>true</UseWindowsForms>

There won't be a visual designer to use, but you should have access to the APIs.

Unfortunately, there is no Winforms designer in Visual Studio 2019 for F# projects of any type, and Winforms can only be easily accessed (as far as I know) in .Net Framework (NOT .NET Core) projects they can be accessed as per @Phillip Carter's answer.

However you can still make Winforms programs easily by manually adding the references to your .NET Framework project, or (more easily) by manually compiling with the F# compiler, fsc.

  • The Fast Way

The easiest way to do this is simply compile the source code with the F# compiler from a single source file with fsc.exe. The F# compiler will automatically resolve dependencies for things like System.Windows.Forms and a lot of other commonly used namespaces. You can also provide lots of compiler directives for requiring other resources as well.

Example using VSCode, with various extensions: VSCode example


  • Another Way

Start a new F# console .NET Framework project (don't pick .NET Core). New Project

Right click on "References" in the Solution Explorer and click "Add Reference..." References

Under assemblies, look for "System.Windows.Forms," select it... Select System.Windows.Forms

And also select "System.Drawing" and then hit OK System.Drawing

Now you have access to both of those namespaces.

Before you run the project in Visual Studio, you should replace

[<STAThread>]
Application.Run( new PendulumForm( Visible=true ) )

with

[<STAThread;EntryPoint>]
let main _ = 
    Application.Run( new PendulumForm( Visible=true ) )
    0

This way you (and VS) know where main actually is. It's not necessary for this small of a program to actually run it, but as your projects get larger VS will complain more about where things are located in your project.

Related